본문 바로가기

Java SE/synchronized

synchronized


Java synchronized

The primary means of ensuring mutual exclusion in Java is through synchronized methods.

methods

In Java, a method may be declared synchronized. In each object at most one synchronized method can run at any one time. We say that a synchronized method obtains a lock on its containing object before it can execute. Since there is only one lock for each object, this prevents any other synchronized method from running until this method completes: no other method can obtain a lock on the object until this method releases its lock. This one-animacy-running-at-a-time property is called mutual exclusion.

public synchronized void methodA() {
   // statements
}


Locking an object only prevents access to other methods or code blocks that also require a lock on the same object. Locking an object does not prevent other (non-synchronized) methods of the object from running, nor does it prevent other use of the object.



(blocks)

Java has a second form of synchronized execution. A special synchronized statement type can be used to provide mutual exclusion on its body. Unlike synchronized methods, the synchronized statement (sometimes called a synchronized block) must explicitly specify the object it locks. The syntax of this statement is:

public void methodB() {
// statements
synchronized ( objectReference ) {    // statements }
}