Using Private Static Final Object Locks for Safe Java Synchronization

The article advises using a private static final Object as a lock to protect critical sections in Java, explains why uncontrolled monitor objects such as this, class objects, or shared interned strings can cause deadlocks, and lists unsafe and safe monitor objects with examples.

Cognitive Technology Team
Cognitive Technology Team
Cognitive Technology Team
Using Private Static Final Object Locks for Safe Java Synchronization

Use a private (static) final Object lock = new Object() to protect critical sections.

Reason

1. Do not use monitor objects whose permissions cannot be controlled.

Do not do this:

Synchronized instance methods or synchronized blocks that use this as the monitor.

Synchronized static methods that use the getClass() monitor.

2. Do not use shared monitor objects; they may cause deadlocks or uncontrolled risks.

Boolean monitor objects

Primitive type monitor objects

Autoboxed type monitor objects

new String("xxx").intern() shared monitor

String lock = "Lock" cached monitor

java.lang.Integer.valueOf(int) cached monitor

getClass() public monitor; subclasses have different monitors

Class name monitor

Class.forName() monitor

You can use the following monitor objects:

private final String lock = new String("LOCK");
private final Object lock = new Object();

3. For static data, use a static monitor object.

Do not do this:

Static data protected by a non‑static monitor.

Synchronized methods using the built‑in monitor to protect static data.

Follow the public account and reply with java e‑book to receive the download link and extraction code.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaBackend DevelopmentconcurrencyLock
Cognitive Technology Team
Written by

Cognitive Technology Team

Cognitive Technology Team regularly delivers the latest IT news, original content, programming tutorials and experience sharing, with daily perks awaiting you.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.