What are the different uses of the synchronized keyword?

Alex Chaffee

The keyword synchronized is used to acquire a exclusive monitor lock on an object. It can be used to mark either a method or a block of code. In both cases, it means to acquire a lock for the duration of the method or block, and to release the lock at the end. It also takes a parameter, which names the object whose lock will be acquired. (The parameter is implicit when marking a method, as shown below.)


synchronized (foo) {
 ...
}
Acquires a lock on the object instance "foo" at the open brace, and releases the lock at the close brace.

synchronized (this) {
 ...
}
Acquires a lock on the current object instance ("this") at the open brace, and releases the lock at the close brace.

synchronized void bar() { 
 ... 
}
Acquires a lock on the current object instance at the open brace, and releases it at the close brace. This is equivalent (*) to
void bar() { 
 synchronized (this) {
  ... 
 }
}

class Foo {
 synchronized static void bar() { 
  ... 
 }
}

Acquires and releases a lock on the class instance of class Foo. Every class, when loaded, is given an instance of class Class. That means that no matter who invokes method Foo.bar(), the lock will be on the static instance, and not on any specific instance of class Foo.

I know this sounds confusing, but it has the same semantics as any other use of static: all statics (methods, variables, etc) are essentially global, interact with all other statics of the same class, and do not interact with non-static instance data.

Whether a method is public or not makes no difference to the semantics of synchronized.

(* Actually, there is a very small, technical difference between void bar() { synchronized (this) { ... } } and synchronized void bar() { ... }: the VM may be able to very slightly optimize the latter case, since the synchronization is marked in the method signature and not in code. However, this is not important in practice.)

See also What does it mean to lock an object?
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact