Pages

6 Nov 2012

Synchronized keyword in Java

2 effects:
  • First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.
  • Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads.

Explanation about lock object of synchronized block:
  • If you synchonize on the method ( as you're doing by typing public synchronized void addA() ) you lock the whole object, so two thread accessing a different variable from this same object would block each other anyway.
  • If you want to syncrhonize only a variable at a time , so two thread wont block each other while accessing different variables, you have to add them in a synchronized block, and use the variable as the "lock" of the block. If a and b were object references you would use:
public void addA() {
    synchronized( a ) {
        a++;
    }
}
public void addB() {
    synchronized( b ) {
        b++;
    }
}


References:
- http://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html
- http://stackoverflow.com/questions/3369287/synchronized-block-lock-object-question
- http://stackoverflow.com/questions/3047564/java-synchronized-method-lock-on-object-or-method

No comments:

Post a Comment

Note: only a member of this blog may post a comment.