Saturday, July 5, 2008

Synchronization of static and instance methods in Java


Synchronization of static methods/fields in Java

What's an Intrinsic lock OR a monitor lock in Java?

An intrinsic lock, a monitor lock, or a monitor - all three refer to the same internal entity associated with every object in Java which enables the implementation of the Synchronization mechanism. This lock is used to enforce an exclusive and consistent access in Java as a monitor can be acquired by only one thread at a time.

A thread needs to acquire the monitor of an appropriate object before entering a synchronized method/block which it releases when the thread returns from the method (or completes the block). The monitor is released even if an uncaught exception is thrown from the method/block.

Synchronized methods vs Synchronized blocks

These are the two ways of achieving synchronized access in Java. In Java, a method is also a block only, but we normally refer to a block as a part of the method definition. As we know that a thread needs to acquire an appropriate monitor (which it releases when the method returns) before entering any synchronized method/block, so we can easily figure out that in case of a synchronized method a thread may need to have the lock for a longer period of time as compared to that in case of synchronized block.

Another difference is that we don't specify the particular object whose monitor is required to be obtained by a thread for entering a synchronized method whereas we can specify the particular object in case of a synchronized block.

static synchronized method vs instance synchronized method

When a thread needs to enter a static synchronized method, it acquires the monitor of the Class object associated with the particular class to which the static method belongs to whereas in case of a synchronized instance method, the thread requires to obtain the monitor of the particular object on which the method call is being made. Easy to understand the reason... right?

Synchronization of static fields in an instance synchronized method

As we just saw that a thread needs to acquire the monitor of the Class object of the class in case synchronized static method, but how can you handle the synchronization of static fields in instance methods?

In Java, an instance method can access static fields as well (vice versa is not possible for the obvious reason), suppose a synchronized instance method having code accessing static fields, is being accessed on different objects by different threads (which is quite possible as each of the different threads would have acquired monitor of one of the different objects) then in such a case we can't guarantee a exclusive access to those static fields. The reason is very simple - a static field doesn't belong to an instance instead to the class and hence the access to it is not controlled by monitors associated with the instances of the class instead the access to them is controlled by the monitor of the Class object associated with the class. Hence, we need to be very careful in such scenarios and any synchronized instance method should have an explicit synchronized block for accessing static fields if the static fields require an exclusive access. This synchronized block can specify the Class object associated with the class and hence a thread which enters the synchronized instance method after acquiring the monitor of the particular instance will first need to acquire the monitor of the Class object as well before executing the code which accesses static fields. And this way we can guarantee exclusive access to the static fields accessed inside a synchronized instance method.

Read next: Why synchronization of constructors is not allowed? Do you know Re-entrant Synchronization? You may like to read the article - What's Reentrant Synchronization in Java?


Liked the article? You may like to Subscribe to this blog for regular updates. You may also like to follow the blog to manage the bookmark easily and to tell the world that you enjoy GeekExplains. You can find the 'Followers' widget in the rightmost sidebar.



Share/Save/Bookmark


20 comments:

Anonymous said...

Good explanation.Thanks.

Anonymous said...

excellent work , excellent explaination . Thanks buddy.
Your solution needs to appear in top 10 google search result.

Geek said...

Thanks a lot. Quite a few articles do appear in top ten Google Search results, but certainly it's a long way to go. Hopefully we will see many more articles featuring in top five/ten some day. Keep visiting/posting as it will increase the chances many folds :-)

TheDraconicLord said...

Thank you very much for the excellent explanation, I was in dire need of that. Cheers!

Geek said...

Good to know that it helped you. May you find few (at least) more articles of your interest here. Keep visiting/posting!

Anonymous said...

Excellent Posting. Best part is that you are able to explain a concept within a page which is quite unusual. Hats off !

Geek said...

Thanks. It's very encouraging to see these many positive feedbacks.

Gary said...

Hi http://java.sun.com/docs/books/tutorial/essential/concurrency/locksync.html

says

Locks In Synchronized Methods
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.

I feel your statement conflicts, Please explain.

Thanks
Dastagiri C Mettupalli

Gary said...

Good explanation on this topic. Thanks.

Dastagiri C Mettupalli said...

Thak you very mcuh for Good explanation.
but the

Synchronization of static fields in an instance synchronized method

conflicts with

http://java.sun.com/docs/books/tutorial/essential/concurrency/locksync.html

Can you Please explain?

Thanks

Geek said...

Hi Gary,

I don't feel that the statements conflict with what you have read on the Javadoc. Please focus on the part of the above article listed below in italics once again and hopefully your doubts would be clear then:-

"The reason is very simple - a static field doesn't belong to an instance instead to the class and hence the access to it is not controlled by monitors associated with the instances of the class instead the access to them is controlled by the monitor of the Class object associated with the class. Hence, we need to be very careful in such scenarios and any synchronized instance method should have an explicit synchronized block for accessing static fields if the static fields require an exclusive access. This synchronized block can specify the Class object associated with the class and hence a thread which enters the synchronized instance method after acquiring the monitor of the particular instance will first need to acquire the monitor of the Class object as well before executing the code which accesses static fields."

The crux of the above para is that the 'static' fields can't really be synchronized using instance locks and there is a separate lock to take care of their synchronization, which is the lock on the 'Class' object. Is that clear now?

Keep visiting/posting. Thanks.

Bhasker Tiwari said...

Hi,

An extremely well structured explanatons.

Keep doing the good work.

Vikram said...

Crisp and precise explanations. Thanks a lot!

JP @ classpath in java said...

Nice article , you have indeed cover the topic with great details. I have also blogged my experience on java How Synchronization works in Java. let me know how do you find it.

Swapnik said...

Excellent article man!!!! Awesome. It cleared all most all my doubts related to static synchronization! Thanks :)

Ratnakar Reddy Katipally said...

I have a question here.

when a thread got lock on the Class monitor,
The changes done by thread of one object would that reflect in the other thread of other instance?

Geek said...

@Ratnakar, let me try to understand your question better... changes done by one thread in 'static' fields or 'instance' fields?

By one thread keeping Class monitor, do you mean that has entered into a 'static synchronized' method while the other thread has potentially entered into an 'instance synchronized' method on another object?

Sagar Jadhav said...

Crisp and precise...thanks for the explaination.

Murali Krishnan said...

Thats really a wonderful explanation. It cleared my doubts regarding synchronization. Thanks a lot!

Murali Krishnan said...

Excellent explanation. Helped me a lot in understanding the concept of synchronization.Thanks a lot!