aspose file tools*
The moose likes Threads and Synchronization and the fly likes static synchronized / synchronized Threads 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 / synchronized Threads" Watch "static synchronized / synchronized Threads" New topic
Author

static synchronized / synchronized Threads

kri shan
Ranch Hand

Joined: Apr 08, 2004
Posts: 1382
Scenario1
------------

Public class Test {

static synchronized int test1() {

}

synchronized int test2() {

}
}

Whether both test1 and test2 will acquire the lock at the same time or after Thread1(calls test1) releases the lock only Thread2(calls test2) will get the lock?

scenario2
-----------
Public class Test {

synchronized int test1() {

}

synchronized int test2() {

}
}

Whether both test1 and test2 will acquire the lock at the same time or after Thread1(calls test1) releases the lock only Thread2(calls test2) will get the lock?
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18981
    
  40



It's pretty easy (and quick) to write a program that will test this. Why don't you take a shot at it, and report back what you see?

Henry


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

Joined: Jun 22, 2009
Posts: 31
If I recall correctly, static and non-static synchronized methods are synchronized on different object, in the latter case it's "this", while in the former it's a class. So these two methods are not really synchronized against each other whatsoever.
Speaking of Scenario 2, these methods are synchronized on "this" so there's no way for them to acquire the lock at the same time a someone will have to wait.


SCJP, SCWCD
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: static synchronized / synchronized Threads