File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Threads Questions? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Threads Questions?" Watch "Threads Questions?" New topic
Author

Threads Questions?

satya mamillapalli
Ranch Hand

Joined: Jun 22, 2005
Posts: 63
WHat is the difference between

public synchronized int read(int a, int b){return a+b;}
public synchronized void set(int a, int b){this.a=a;this.b=b;}

and

public int read(int a, int b){synchronized(this){return a+b;}}
public void set(int a, int b){synchronized(this){this.a=a;this.b=b;}}


synchronized vs synchronized(this)???

Please Advise..
[ August 30, 2005: Message edited by: satya mamillapalli ]
Santana Iyer
Ranch Hand

Joined: Jun 13, 2005
Posts: 335
synchornized(this) { }

only synchronizes a block of code, this means object that has invoked this method you can also specify object on which you want lock.

while synchronized modifier in method signature means whole method
is synchronized.

when you only want only some code to be synchronized use synchronized(this) { } as it affects only part of method,

synchronized in method means complete method is synchorinzed.
Michael Ernest
High Plains Drifter
Sheriff

Joined: Oct 25, 2000
Posts: 7292

The difference is twofold. If a method is marked synchronized, the thread entering must acquire the object lock before it can enter the method and begin work. As a statement, the synchronized requires the thread to acquire the object lock before it can go any further in the method.

It is also possible (but not generally advisable) for the synchronized statement to name an object lock other than the 'this' object lock.

The different in the statements you've written is pretty small, since the the synchronized statement is the first instruction inside the method. In this case, however, it is possible for an arbitrary number of threads to enter these methods and then contend for the object lock.


Make visible what, without you, might perhaps never have been seen.
- Robert Bresson
 
 
subject: Threads Questions?
 
Similar Threads
Doubt in K&B Question on Thread
Why autoboxing doesnt work here???
synchronized
Thread question
Threas - Object Locks Question