Monday, March 28, 2011

Java syncronized methods

The synchronized keyword indicates that a method can be accessed by only one
thread at a time.

public synchronized BagContainer readBag( int bagId ) {
// do getting of object
}

When a thread invokes a synchronized method, it automatically acquires the intrinsic lock for that method's object and releases it when the method returns. The lock release occurs even if the return was caused by an uncaught exception.

You might wonder what happens when a static synchronized method is invoked, since a static method is associated with a class, not an object. In this case, the thread acquires the intrinsic lock for the Class object associated with the class. Thus access to class's static fields is controlled by a lock that's distinct from the lock for any instance of the class.

No comments:

Post a Comment