• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Threads Questions?

 
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
Ranch Hand
Posts: 335
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
High Plains Drifter
Posts: 7289
Netbeans IDE VI Editor
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic