GeeCON Prague 2014*
The moose likes Threads and Synchronization and the fly likes static synchronized vs non-static synchronized Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "static synchronized vs non-static synchronized" Watch "static synchronized vs non-static synchronized" New topic
Author

static synchronized vs non-static synchronized

Sridhar Gudipalli
Ranch Hand

Joined: Nov 02, 2005
Posts: 120
Hi All,

Source: self written program



output:
main bMethod..
s1 running
s1 aMethod..
s1 aMethod..
main bMethod..
s1 aMethod..
s1 aMethod..
main bMethod..
s1 aMethod..
main bMethod..
main bMethod..

My question is.. whenever s1 got lock on Class object how the main bMethod is getting executed? (I know static synchronized acquires lock on monitor associated with Class and non-static synchronized method acquires lock on monitor associated with instance)

Could anyone explain in detail please?

Sridhar Gudipalli|SCJP 6.0
SCWCD objectives
Tom Reilly
Rancher

Joined: Jun 01, 2010
Posts: 618
My question is.. whenever s1 got lock on Class object how the main bMethod is getting executed? (I know static synchronized acquires lock on monitor associated with Class and non-static synchronized method acquires lock on monitor associated with instance)

I studied your question for a while (OK, 3 minutes) and am not clear on your confusion. Are you thinking that there is a hierarchy of synchronizing between class and instances? That is, much like in a database you can lock a row in a table or lock a whole table (which locks all rows)? You can lock on a class or on an instance of a class. If Thread A gains a lock on a class and thread B tries to get the same class lock then thread B will wait. However, if thread B tries to get a lock on an instance of class A then it will not have to wait because the two threads are using two different locks.
Sridhar Gudipalli
Ranch Hand

Joined: Nov 02, 2005
Posts: 120
1) Whenever s1 thread started it acquires a lock on class.
2) Whenever s2.bMethod() is called it tries to get the lock on the instance.

My confusion was..... If this s1 holds lock on class, again how come s2 can acquire lock on that instance? Lock on Class means only lock on "static synchorized methods" or all the synchronized methods in class?
Tom Reilly
Rancher

Joined: Jun 01, 2010
Posts: 618
Sridhar Gudipalli wrote:1) Whenever s1 thread started it acquires a lock on class.
2) Whenever s2.bMethod() is called it tries to get the lock on the instance.

My confusion was..... If this s1 holds lock on class, again how come s2 can acquire lock on that instance? Lock on Class means only lock on "static synchronized methods" or all the synchronized methods in class?

First, the JVM always lock on an object instance. All object locks are "separate but equal". (Take special note the difference between Class and class in the next sentences.) When you synchronize on a static method, the JVM uses the instance of the Class class that is associated with the static method's class. So in this case, all synchronized static methods of the class are locked because there is only one instance of Class for each class. When you synchronise on an instance (non-static) method, the JVM uses the instance of the class. In this case, only that method is locked. So the answer to your question is:
Lock on Class means only lock on "static synchronized methods"
Sridhar Gudipalli
Ranch Hand

Joined: Nov 02, 2005
Posts: 120
Thanks Tom. Now its clear.
Threads is the area that I didnot do well in SCJP 6.0. So, trying to get hold of it.
Tom Reilly
Rancher

Joined: Jun 01, 2010
Posts: 618
Threads is the area that I didnot do well in SCJP 6.0. So, trying to get hold of it.

Threads give me a headache :-)
Jim Hoglund
Ranch Hand

Joined: Jan 09, 2008
Posts: 525
I suggest that we say "the method is waiting for the lock" rather than saying
"the method is locked." Many become very confused about synchronization
thinking that methods are locked, rather than objects.

Jim ... ...


BEE MBA PMP SCJP-6
Abimaran Kugathasan
Ranch Hand

Joined: Nov 04, 2009
Posts: 2066

Try this code...


|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|
Jim Hoglund
Ranch Hand

Joined: Jan 09, 2008
Posts: 525
Below is the same code, just slimmed down a bit. When s1.start() is called, s1 grabs its
own 'this' object lock and holds it for the entire run. Similarly, when statSync() is called,
it grabs the Class object lock and holds it for the entire run. The output just shows the
JVM swapping the two threads in and out. Jim ... ...
Gladwin Burboz
Greenhorn

Joined: Feb 26, 2008
Posts: 25

Lock is the feature of an object, not of a method or a class or a thread. Thread that needs exclusive access to a particular instance, acquires lock of that object by using synchronized method or a block.

For a given class, you can have multiple object instances each having it's own lock.
For a given class, you can have one and only one class-object instance having only one lock.

Thread acquires lock of an object instance or class-object instance.
Only one thread can acquire lock of a given object at a time.

Thread calling synchronized instance method will acquire lock on that object instance.
Thread calling synchronized static method will acquire lock on class-object instance.

Having said above,
if thread acquires lock on one of the object instance of a given class will not prevent some other thread to acquire lock of a class-object instance
.

<a href="http://www.sealordresortarnala.com" target="_blank" rel="nofollow">http://www.sealordresortarnala.com</a>
Apurva Goyani
Greenhorn

Joined: Jun 23, 2010
Posts: 3
Gladwin Burboz wrote:
Lock is the feature of an object, not of a method or a class or a thread. Thread that needs exclusive access to a particular instance, acquires lock of that object by using synchronized method or a block.

For a given class, you can have multiple object instances each having it's own lock.
For a given class, you can have one and only one class-object instance having only one lock.

Thread acquires lock of an object instance or class-object instance.
Only one thread can acquire lock of a given object at a time.

Thread calling synchronized instance method will acquire lock on that object instance.
Thread calling synchronized static method will acquire lock on class-object instance.

Having said above,
if thread acquires lock on one of the object instance of a given class will not prevent some other thread to acquire lock of a class-object instance
.



Hi Gladwin,
I agree to what you said, but just one question ponders me is that when two threads have access to two methods (1 static and other non-static respectively) simultaneously how it will access static field (val from StaticSynchronizedDemo), won't it will lead to violation of integrtiy?
Gladwin Burboz
Greenhorn

Joined: Feb 26, 2008
Posts: 25
Apurva Goyani wrote:
Hi Gladwin,
I agree to what you said, but just one question ponders me is that when two threads have access to two methods (1 static and other non-static respectively) simultaneously how it will access static field (val from StaticSynchronizedDemo), won't it will lead to violation of integrtiy?


You can synchronize access to this variable using synchronized block that should attempt to acquire lock on class object as shown below.



However if you are using Java 5 or above, it will be wise to use Lock object instead.
Jim Hoglund
Ranch Hand

Joined: Jan 09, 2008
Posts: 525
Gladwin : I don't understand the last comment about using a lock
object for Java 5 or above. Can you explain further? Thanks.

Jim ... ...
Gladwin Burboz
Greenhorn

Joined: Feb 26, 2008
Posts: 25
See tutorial on Lock Object (http://java.sun.com/docs/books/tutorial/essential/concurrency/newlocks.html) ...
Apurva Goyani
Greenhorn

Joined: Jun 23, 2010
Posts: 3
Gladwin Burboz wrote:
Apurva Goyani wrote:
Hi Gladwin,
I agree to what you said, but just one question ponders me is that when two threads have access to two methods (1 static and other non-static respectively) simultaneously how it will access static field (val from StaticSynchronizedDemo), won't it will lead to violation of integrtiy?


You can synchronize access to this variable using synchronized block that should attempt to acquire lock on class object as shown below.





But this has not been the case in the example StaticSynchronizedDemo(the very first thread) which has not used such lock for accessing the static variable.


Jim Hoglund
Ranch Hand

Joined: Jan 09, 2008
Posts: 525
Gladwin : My question is about the "since Java 5" part of your comment,
since object locking has been around much longer than that. Also, it is
recommended in a multi-thread environment, that only sync'd static
methods operate on the static variables. Sync'd non-static methods
should be restricted to working with only non-static variables. Access
to all variables should be private.

Jim ... ...
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3016
    
  10
Jim Hoglund wrote:Gladwin : My question is about the "since Java 5" part of your comment,
since object locking has been around much longer than that.

If you follow the two links Gladwin provided, it's clear both posts referred to java.util.concurrent.locks.Lock - which has only been around since Java 5.
Alpesh Padra
Ranch Hand

Joined: Jan 10, 2010
Posts: 41
When Synchronization is applied on a static Member or a static block, the lock is performed on the Class and not on the Object, while in the case of a Non-static block/member, lock is applied on the Object and not on class. [Trail 2: There is a class called Class in Java whose object is associated with the object(s) of your class. All the static members declared in your class will have reference in this class(Class). As long as your class exists in memory this object of Class is also present. Thats how even if you create multiple objects of your class only one Class object is present and all your objects are linked to this Class object. Even though one of your object is GCed after some time, this object of Class is not GCed untill all the objects associated with it are GCed.
This means that when ever you call a "static synchronized" block, JVM locks access to this Class object and not any of your objects. Your client can till access the non-static members of your objects.

Apurva Goyani
Greenhorn

Joined: Jun 23, 2010
Posts: 3

You can synchronize access to this variable using synchronized block that should attempt to acquire lock on class object as shown below.





But this has not been the case in the example StaticSynchronizedDemo(the very first thread) which has not used such lock for accessing the static variable.


Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3016
    
  10
Apurva Goyani wrote:But this has not been the case in the example StaticSynchronizedDemo(the very first thread) which has not used such lock for accessing the static variable.

Well, there weren't any static variables anywhere in that class anyway, so it's a non-issue. But there was a static synchronized method, which is equivalent to the synchronized(StaticSynchronizedDemo.class) lock that you showed.
Jim Hoglund
Ranch Hand

Joined: Jan 09, 2008
Posts: 525
Mike : Thanks. I missed the "Lock" and read "lock" instead. But this leads to another
question. Given the original post, why should Lock be used over the simpler object
locking mechanism (ref: the "keep-it-simple" principle)?

Jim ... ...
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18874
    
  40

Jim Hoglund wrote:Mike : Thanks. I missed the "Lock" and read "lock" instead. But this leads to another
question. Given the original post, why should Lock be used over the simpler object
locking mechanism (ref: the "keep-it-simple" principle)?


Under some conditions, the "simplier" mechanism may be a bit too simple. No control of fairness in granting locks. No way to prevent interruption. No way to timeout a lock grab. No way to check how many threads are waiting for the lock.... and probably the biggest issue... No way to have more than one condition variable per lock.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Jim Hoglund
Ranch Hand

Joined: Jan 09, 2008
Posts: 525
Thanks Henry. Sounds like I need to get into the Lock business as there are
some handy features. As far as the lone condition variable, however, can not
the lock object be a very statefull class?

Jim ... ...
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3016
    
  10
Well, yes - that's basically the point of conditions. They're similar to wait-notify, where one or more threads want to wait until something changes in response to another thread. "Something" is mutable state - if it weren't mutable, there would be nothing to wait for, and no need for a wait/notify-like protocol.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18874
    
  40


A "condition variable" is a very specific term regarding threads -- and not just a variable that holds a condition. With synchronization, it is implemented via the wait() and notify() methods. With the Lock class (interface), it is implemented with the Condition class (interface).


The classic case of needing more than one condition variable per lock, is the case of a bounded data structure. If a thread needs to put data into the structure, but it is full, then it needs to wait(). Also, if a thread needs to take data from the structure, but it is empty, then it needs to wait(). So... in both cases, the wait() and notify() mechanism will work.

However, you only have one lock (synch on the data structure), so you only have one object for notification. You can uses two objects for notification, but then the locking will get very complex, as there will be code that will need both locks. You can use notifyAll() instead, and let the threads work it out, but if there are thousands of threads, it will be ridiculously inefficient.

So... in this example, the best option is to use the Lock class, which can provided two Condition classes, that share the same lock. One condition for full. And one condition for empty.

Henry
Jim Hoglund
Ranch Hand

Joined: Jan 09, 2008
Posts: 525
Thanks again Henry.

Jim ... ...
 
GeeCON Prague 2014
 
subject: static synchronized vs non-static synchronized