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 block syntax 1

Status
Not open for further replies.

Sedai

Programmer
Mar 4, 2001
158
US
i need to synchronize a method, but actually only part of it needs to be locked, so i wanted to use {} synchornization instead of freezing the whole method.

I thought that the syntax was the following:

synchronized {
//code
}

but it doesnt compile. apparently, there needs to be something in () brackets before the {}
Can anyone clarify what exactly I'm supposed to put there and what's the purpose of that ;) Thanks.

Avendeval


 
The thing that is placed in the () in a synchronized code block is known as a monitor. This must be an Object.

Syntax:
Code:
synchronized(Object) { }
The thread entering the synchronized code block acquires a lock on the monitor in a single atomic operation when it first enters and releases this lock upon exit of the code block. All other threads trying to enter must block or wait until the monitor is released. An easy Object to use as the monitor is a reference to this if the method is an instance method or a simple static variable if the method is static.

Code:
public class Test {
  private static Object monitor = new Object();

  public static void testStaticMethod() {
    synchronized (monitor) { ... }
  }

  public void testInstanceMethod() {
    synchronized (this) { }
  }
}
 
that makes a lot of things clear. What I've read about stop() and suspend() being dangerous in that they release monitors that might be locking other parts of the code, etc, or something like that. Now it makes sense. Thanks.
Avendeval


 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top