Object-level locking is it thread-safe?

Viewed 75

I have implemented locking at the object level for accessing the device:

private static Object device_locker_ = new Object();

public Device getDevice() {
 synchronized (device_locker_) {
    return device_;
 }
}

Can different threads in this case work with the device, calling different methods through getDevice()? Examples:

getDevice().getDeviceInfo()
getDevice().changePIN()
getDevice().doSomething()

All threads work with one instance of the class in which the getDevice () method is defined.

Is it guaranteed in this case that only one thread can work with the device?

2 Answers

Can different threads in this case work with the device, calling different methods through getDevice()? Examples:

getDevice().getDeviceInfo()
getDevice().changePIN()
getDevice().doSomething()

No. Different threads cannot safely work with the same instance returned by getDevice(), because (based on the method names I am assuming) that the content of the instance returned by getDevice() is being modified within those methods (e.g., changePIN()).

This :

public Device getDevice() {
 synchronized (device_locker_) {
    // This is the safe zone
 }
}

only guarantees that only one thread of those that are holding the lock device_locker_ can access the code within the synchronized(device_locker_ ) clause. If you leak the object outside then the object is out of the scope of the synchronized clause and therefore can be accessed by multithreads in a non thread safe manner. Just like when you are at home your roof protects you from the rain, but if you go outside then you are in your own.

All threads work with one instance of the class in which the getDevice () method is defined.

Is it guaranteed in this case that only one thread can work with the device?

That does not matter, as long as getDevice returns the same Object memory reference that is shared among threads, there is a risk for race-conditions, and data races, if the proper care is not taken (e.g., ensuring mutual exclusion of the accesses to the shared resource).

What is the point of synchronizing a read-only method? You should synchronize the blocks/methods where state of the device object changes.

Related