Panasonic Youth

Notes on synchronzied methods and code blocks

Just making some notes on the use of sychronized.

[java]public void synchronized doStuff() { // do stuff }[/java]

..is equivalent to:

[java]public void doStuff{} { synchronized(this) { // do stuff } }[/java]

The lock is on the object instance. Any synchronized instance methods will be locked out while doStuff() processes. For static methods:

[java]public static void synchronized doStuff() { // do stuff }[/java]

is the same as:

[java]public static void doStuff() { synchronized(ThisClass.class) { // do stuff } }[/java]

in that the lock is on the class object. Further reading: