Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Threads Questions?

 
satya mamillapalli
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 335
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 7292
Netbeans IDE VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic