Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

synchronized methods and block?

Status
Not open for further replies.

drkestrel

MIS
Sep 25, 2000
439
GB
In a class with synchronized methods and synchronized blocks. Are the monitor objects that govern the synronized methods and synchronized blocks the same, assuming that
1) the synchronized block is locking on a object defined within the class OR
2) the synchronized block is locking on the class itself (this)

i.e. if I have a class that implements Runnable as follows
could I be sured that the two synchronized methods and the synchronized block are all mutually exclusive?


Code:
private Boolean on;
public synchronized void setOn()
{
   on = new Boolean(true);
}

public synchronized void setOff()
{
   on = new Boolean(false);
}

public void run()
{
  synchronized (this)
  {
     if (on.booleanValue())
     {
          //do some processing
     }
  }
}
 
Hi,

Where you have a synchronized method, the method waits until it gets a lock on its object (this).

Where you have a synchronized block, it waits until it gets a lock on that object.

So the following is satisfactory:

private Boolean on;
public synchronized void setOn()
{
on = new Boolean(true);
}

public synchronized void setOff()
{
on = new Boolean(false);
}

public void run()
{
synchronized (this)
{
// No other thread can call setOff() or setOn() at this point.
}
}

You should also make your member variable 'on' volatile:


private volatile Boolean on;


If something is likely to be accessed through different threads, setting a member as volatile ensures that Java runtime does not make any assumptions about the value of the member. Java may otherwise use cached memory values for speed, which are not thread-safe.

scrat
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top