Search code examples
javamultithreadingthread-safetysynchronized

Thread safety "synchronized": by example


Good afternoon!

Inside class B, a method is defined using the keyword "synchronized". Inside this method, you work with an object of class A, which is publicly available. Tell me, please, is thread safety guaranteed for object A in this case? I.e. synchronized will be applied to a separate instance of B, not focusing on A - "synchronized(this { } == synchronized(B) { }"? For greater thread safety, is it necessary to use a block of the type "synchronized(A) { }"?

The question is caused by the fact that the first example in practice still does not work thread-safe, although this is the only method of correcting a public object. I'm figuring out why.

Thanks for the reply.

public class B {

    public synchronized void updateA(A a) {
        ....
    }

}

public class B {

    public void updateA(A a) {
        synchronized (this) {
            ....
        }        
    }

}

public class B {

    public void updateA(A a) {
        synchronized (a) {
            ....
        }        
    }

}

Solution

  • Using synchronized keyword in the method signature means that when one thread use this method it lock monitor on this object and no other threads can use this method of this instance until first thread release it. It does not lock any other methods or A object. Only part of code inside synchronized block. So if two separate instances of 'B' modify the same 'a' object it won't be locked.

    First and second examples in your question are the same in meaning.

    Third example with synchronized (a) means that for synchronization will be used monitor of the a object.

    synchronized will be applied to a separate instance of B

    In your code synchronized uses different monitors for each instance. To provide synchronization for all instances you need to define common monitor, for example synchronized (B.class) or synchronized (A.class).

    For greater thread safety, is it necessary to use a block of the type "synchronized(A) { }"?

    If you want to avoid concurrency using of a object you need to lock on a.