Let’s imagine that we have some kind of public global map which entities’ monitors are used in synchronized blocks in different methods of other classes. In some moment we remove entities from our collection and garbage collector removes it from application memory.
Sample code is below:
public final class LockTable {
public static final Map<String, Object> lockers = new HashMap<>();
}
public class FirstClass {
public void methodWithRemovingKey() throws InterruptedException {
String someKey = "someKey";
new Thread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
System.out.println("Removing key " + someKey);
LockTable.lockers.remove(someKey);
}).start();
new SecondClass().methodWithSynchronizedBlock(someKey);
}
public static void main(String[] args) throws InterruptedException {
new FirstClass().methodWithRemovingKey();
}
}
public class SecondClass {
public void methodWithSynchronizedBlock(String key) throws InterruptedException {
System.out.println("Entered methodWithSynchronizedBlock");
synchronized (LockTable.lockers.computeIfAbsent(key, k-> new Object())) {
System.out.println("Synchronized object is used " + LockTable.lockers.get(key));
Thread.sleep(10000);
System.out.println("Synchronized object was used " + LockTable.lockers.get(key));
}
System.out.println("Exit methodWithSynchronizedBlock");
}
}
If we run main method in the FirstClass we will see that our object used in synchronized block is removed. The program output:
Entered methodWithSynchronizedBlock
Synchronized object is used java.lang.Object@96532d6
Removing key someKey
Synchronized object was used null
Exit methodWithSynchronizedBlock
What will happened with our synchronization if such scenario appears in concurrent environment? Will it be removed?
1
There is no such thing as “deleting an object” in Java.
Just because you removed the object from some map, it does not mean that the object was in any way, shape, or form, deleted.
The object will be “deleted” (correct terminology: “finalized and collected”) by the garbage collector when it is not being referenced anymore.
And the object will, of course, continue being referenced for as long as it is locked by the synchronized
clause.