You are on page 1of 10

7/14/13

static synchronized vs non-static synchronized (Threads forum at JavaRanch)

A friendly place for programming greenhorns!

Big Moose Saloon


Search

Java FAQ

Recent Topics

Register / Login

JavaRanch Java Forums Java Threads and Synchronization

Author
Sridhar Gudipalli Ranch Hand Joined: Nov 02, 2005 Posts: 120

static synchronized vs non-static synchronized


posted 6/23/2010 12:35:53 AM

Hi All, Source: self written program

view plain

c opy to c lipboard

print

N ote: T ext c ontent in the c ode bloc ks is automatic ally word- wrapped

0 1 . 0 2 . 0 3 . 0 4 . 0 5 . 0 6 . 0 7 . 0 8 . 0 9 . 1 0 . 1 1 . 1 2 . 1 3 . 1 4 . 1 5 . 1 6 . 1 7 . 1 8 . 1 9 . 2 0 . 2 1 . 2 2 .

p u b l i cc l a s sS t a t i c S y n c h r o n i z e d D e m oe x t e n d sT h r e a d { p u b l i cS t a t i c S y n c h r o n i z e d D e m o ( S t r i n gn a m e ){ s u p e r ( n a m e ) ; } p u b l i cs t a t i cs y n c h r o n i z e dv o i da M e t h o d ( ) { f o r ( i n ti = 0 ; i < 5 ;i + + ) { S y s t e m . o u t . p r i n t l n ( T h r e a d . c u r r e n t T h r e a d ( ) . g e t N a m e ( ) + "a M e t h o d . ." ) ; t r y{ s l e e p ( 2 0 0 0 ) ; }c a t c h( I n t e r r u p t e d E x c e p t i o ne ){ e . p r i n t S t a c k T r a c e ( ) ; } } }

p u b l i cs y n c h r o n i z e dv o i db M e t h o d ( ) { f o r ( i n ti = 0 ; i < 5 ;i + + ) { S y s t e m . o u t . p r i n t l n ( T h r e a d . c u r r e n t T h r e a d ( ) . g e t N a m e ( ) + "b M e t h o d . ." ) ; 2 3 . t r y{ 2 4 . s l e e p ( 3 0 0 0 ) ; 2 5 . }c a t c h( I n t e r r u p t e d E x c e p t i o ne ){ 2 6 . e . p r i n t S t a c k T r a c e ( ) ; 2 7 . } https://www.coderanch.com/t/500217/threads/java/static-synchronized-static-synchronized

1/10

7/14/13

2 7 . 2 8 . 2 9 . 3 0 . 3 1 . 3 2 . 3 3 . 3 4 . 3 5 . 3 6 . 3 7 . 3 8 . 3 9 . 4 0 . 4 1 . 4 2 . 4 3 . 4 4 .

static synchronized vs non-static synchronized (Threads forum at JavaRanch) } } }

@ O v e r r i d e p u b l i cv o i dr u n ( ){ S y s t e m . o u t . p r i n t l n ( T h r e a d . c u r r e n t T h r e a d ( ) . g e t N a m e ( ) + "r u n n i n g " ) ; a M e t h o d ( ) ; } p u b l i cs t a t i cv o i dm a i n ( S t r i n g [ ]a r g s ){ S t a t i c S y n c h r o n i z e d D e m os 1=n e wS t a t i c S y n c h r o n i z e d D e m o ( " s 1 " ) ; S t a t i c S y n c h r o n i z e d D e m os 2=n e wS t a t i c S y n c h r o n i z e d D e m o ( " s 2 " ) ; s 1 . s t a r t ( ) ; s 2 . b M e t h o d ( ) ; } }

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|SC JP 6.0 SC WC D objectives

Tom Reilly Rancher Joined: Jun 01, 2010 Posts: 618

posted 6/23/2010 1:53:42 AM

My question is.. whenever s1 got lock on C lass object how the main bMethod is getting executed? (I know static synchronized acquires lock on monitor associated with C lass 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

posted 6/23/2010 2:30:39 AM Gudipalli Ranch Hand 1) Whenever s1 thread started it acquires a lock on class. https://www.coderanch.com/t/500217/threads/java/static-synchronized-static-synchronized

2/10

7/14/13 Ranch Hand


Joined: Nov 02, 2005 Posts: 120

static synchronized vs non-static synchronized (Threads forum at JavaRanch)

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

posted 6/23/2010 3:39:10 AM


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 C lass 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 C lass means only lock on "static synchronized methods"

Sridhar Gudipalli Ranch Hand Joined: Nov 02, 2005 Posts: 120

posted 6/23/2010 5:30 AM

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

posted 6/23/2010 5:35:04 AM

Threads is the area that I didnot do well in SC JP 6.0. So, trying to get hold of it.

Threads give me a headache :-)

Jim Hoglund Ranch Hand Joined: Jan 09, 2008 Posts: 525

posted 6/23/2010 7:37:47 PM

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 SC JP-6 Abimaran Kugathasan Ranch Hand

posted 6/25/2010 8:45:28 PM

Try this code...


3/10

https://www.coderanch.com/t/500217/threads/java/static-synchronized-static-synchronized

7/14/13
Joined: Nov 04, 2009 Posts: 2066
I like...

static synchronized vs non-static synchronized (Threads forum at JavaRanch)


view plain c opy to c lipboard print ?

N ote: T ext c ontent in the c ode bloc ks is automatic ally word- wrapped

0 1 . 0 2 . 0 3 . 0 4 . 0 5 . 0 6 . 0 7 . 0 8 . 0 9 . 1 0 . 1 1 . 1 2 . 1 3 . 1 4 . 1 5 . 1 6 . 1 7 . 1 8 . 1 9 . 2 0 . 2 1 . 2 2 . 2 3 . 2 4 . 2 5 . 2 6 . 2 7 . 2 8 . 2 9 . 3 0 . 3 1 . 3 2 . 3 3 . 3 4 . 3 5 . 3 6 .

p u b l i cc l a s sS t a t i c S y n c h r o n i z e d D e m oe x t e n d sT h r e a d { p u b l i cS t a t i c S y n c h r o n i z e d D e m o ( S t r i n gn a m e ){ s u p e r ( n a m e ) ; } p u b l i cs t a t i cs y n c h r o n i z e dv o i da M e t h o d ( ) { f o r ( i n ti = 0 ; i < 5 ;i + + ) { S y s t e m . o u t . p r i n t l n ( T h r e a d . c u r r e n t T h r e a d ( ) . g e t N a m e ( )+"a M e t h o d . ." ) ; t r y{ s l e e p ( 2 0 0 0 ) ; }c a t c h( I n t e r r u p t e d E x c e p t i o ne ){ e . p r i n t S t a c k T r a c e ( ) ; } } } p u b l i cs t a t i cs y n c h r o n i z e dv o i db M e t h o d ( ) { f o r ( i n ti = 0 ; i < 5 ;i + + ) { S y s t e m . o u t . p r i n t l n ( T h r e a d . c u r r e n t T h r e a d ( ) . g e t N a m e ( )+"b M e t h o d . ." ) ; t r y{ s l e e p ( 3 0 0 0 ) ; }c a t c h( I n t e r r u p t e d E x c e p t i o ne ){ e . p r i n t S t a c k T r a c e ( ) ; } } } p u b l i cv o i dr u n ( ){ S y s t e m . o u t . p r i n t l n ( T h r e a d . c u r r e n t T h r e a d ( ) . g e t N a m e ( )+"r u n n i n g " ) ; a M e t h o d ( ) ; } p u b l i cs t a t i cv o i dm a i n ( S t r i n g [ ]a r g s ){ S t a t i c S y n c h r o n i z e d D e m os 1=n e wS t a t i c S y n c h r o n i z e d D e m o ( " s 1 " ) ; S t a t i c S y n c h r o n i z e d D e m os 2=n e wS t a t i c S y n c h r o n i z e d D e m o ( " s 2 " ) ; s 1 . s t a r t ( ) ; s 2 . b M e t h o d ( ) ; } }

|BSc in Electronic Eng| |SC JP 6.0 91%| |SC WC D 5 92%|

Jim Hoglund Ranch Hand Joined: Jan 09, 2008 Posts: 525

posted 6/26/2010 7:03:36 PM

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.
view plain c opy to c lipboard print ?

N ote: T ext c ontent in the c ode bloc ks is automatic ally word- wrapped

0 1 . 0 2 . 0 3 . 0 4 . 0 5 . 0 6 . 0 7 .

c l a s sS t a t i c S y n ce x t e n d sT h r e a d{ s t a t i cs y n c h r o n i z e dv o i ds t a t S y n c ( ){ f o r( i n ti=0 ;i<1 0 ;i + + ){ t r y{ s l e e p ( 5 0 0 ) ; S y s t e m . o u t . p r i n t l n ( T h r e a d . c u r r e n t T h r e a d ( ) . g e t N a m e ( )+"i = "+ i ) ; }c a t c h( E x c e p t i o ne ){e . p r i n t S t a c k T r a c e ( ) ;} } }

0 8 . 0 9 . 1 0 . 1 1 . 1 2 . p u b l i cv o i dr u n ( ){ https://www.coderanch.com/t/500217/threads/java/static-synchronized-static-synchronized

4/10

7/14/13

1 2 . 1 3 . 1 4 . 1 5 . 1 6 . 1 7 . 1 8 . 1 9 . 2 0 . 2 1 . 2 2 . 2 3 . 2 4 . 2 5 . 2 6 . 2 7 . 2 8 . Jim ...

static synchronized vs non-static synchronized (Threads forum at JavaRanch) p u b l i cv o i dr u n ( ){ s y n c h r o n i z e d( t h i s ){ f o r( i n ti=0 ;i<1 0 ;i + + ){ t r y{ s l e e p ( 5 0 0 ) ; S y s t e m . o u t . p r i n t l n ( T h r e a d . c u r r e n t T h r e a d ( ) . g e t N a m e ( )+"i = "+i ) ; }c a t c h( E x c e p t i o ne ){e . p r i n t S t a c k T r a c e ( ) ;} } } }

p u b l i cs t a t i cv o i dm a i n ( S t r i n g [ ]a r g s ){ S t a t i c S y n cs 1=n e wS t a t i c S y n c ( ) ; s 1 . s t a r t ( ) ; S t a t i c S y n c . s t a t S y n c ( ) ; } } ...

Gladwin Burboz Greenhorn Joined: Feb 26, 2008 Posts: 25

posted 6/26/2010 8:19:34 PM

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

posted 7/2/2010 10:35:36 AM


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.

https://www.coderanch.com/t/500217/threads/java/static-synchronized-static-synchronized

5/10

7/14/13

static synchronized vs non-static synchronized (Threads forum at JavaRanch)


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

posted 7/3/2010 3:00:48 AM

A purva 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.

view plain

c opy to c lipboard

print

N ote: T ext c ontent in the c ode bloc ks is automatic ally word- wrapped

0 1 . 0 2 . 0 3 . 0 4 . 0 5 .

s y n c h r o n i z e d ( S t a t i c S y n c h r o n i z e d D e m o . c l a s s ){ / /C o d et h a tw i l la c c e s ss t a t i cs h a r e dv a r i a b l e }

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

posted 7/3/2010 3:29:21 AM

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

posted 7/3/2010 11:23:57 PM

See tutorial on Lock Object (http://java.sun.com/docs/books/tutorial/essential/concurrency/newlocks.html) ...

Apurva Goyani posted 7/5/2010 5:53:21 PM https://www.coderanch.com/t/500217/threads/java/static-synchronized-static-synchronized

6/10

7/14/13
Greenhorn Joined: Jun 23, 2010 Posts: 3

static synchronized vs non-static synchronized (Threads forum at JavaRanch) posted 7/5/2010 5:53:21 PM
Gladwin Burboz wrote: A purva 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.

view plain

c opy to c lipboard

print

N ote: T ext c ontent in the c ode bloc ks is automatic ally word- wrapped

0 1 . 0 2 . 0 3 . 0 4 . 0 5 .

s y n c h r o n i z e d ( S t a t i c S y n c h r o n i z e d D e m o . c l a s s ){ / /C o d et h a tw i l la c c e s ss t a t i cs h a r e dv a r i a b l e }

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

posted 7/7/2010 1:50:29 AM

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: 2837

posted 7/7/2010 7:21:15 AM


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 posted 7/7/2010 8:17:34 AM

Joined: Jan 10, When Synchronization is applied on a static Member or a static block, the lock is performed on the 2010 https://www.coderanch.com/t/500217/threads/java/static-synchronized-static-synchronized

7/10

7/14/13 2010 Posts: 41

static synchronized vs non-static synchronized (Threads forum at JavaRanch)

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

posted 7/7/2010 10:58:30 AM

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

view plain

c opy to c lipboard

print

N ote: T ext c ontent in the c ode bloc ks is automatic ally word- wrapped

0 1 . 0 2 . 0 3 . 0 4 . 0 5 .

s y n c h r o n i z e d ( S t a t i c S y n c h r o n i z e d D e m o . c l a s s ){ / /C o d et h a tw i l la c c e s ss t a t i cs h a r e dv a r i a b l e }

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: 2837

posted 7/7/2010 11:20:17 AM


A purva 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

posted 7/7/2010 6:38:19 PM

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

posted 7/7/2010 7:33:36 PM

https://www.coderanch.com/t/500217/threads/java/static-synchronized-static-synchronized

8/10

7/14/13
Joined: Sep 28, 2004 Posts: 17009

static synchronized vs non-static synchronized (Threads forum at JavaRanch)


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)?

21
I like...

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

posted 7/8/2010 7:46:35 AM

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: 2837

posted 7/8/2010 11:55 AM

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: 17009

posted 7/8/2010 5:46:17 PM

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).

21 The classic case of needing more than one condition variable per lock, is the case of a bounded data
I like...

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

https://www.coderanch.com/t/500217/threads/java/static-synchronized-static-synchronized

9/10

7/14/13
Jim Hoglund Ranch Hand Joined: Jan 09, 2008 Posts: 525

static synchronized vs non-static synchronized (Threads forum at JavaRanch)


posted 7/8/2010 7:54:45 PM

Thanks again Henry. Jim ... ...

I agree. Here's the link: http://aspose.com/file-tools

subject: static synchronized vs non-static synchronized

Similar Threads Beginner: Threads vs. Runnables After notify() synchronized methods and blocks worries synchronize method call synchronized threads
All times above are in your local time zone & format.T he current ranch time (not your local time) is Jul 14, 2013 09:07:04 .

Contact Us | Powered by JForum |

C opyright 1998-2013 Paul W he aton

https://www.coderanch.com/t/500217/threads/java/static-synchronized-static-synchronized

10/10

You might also like