Java synchronized statement

Java synchronized statement

Java associates a lock with every object. Consequently in the previous example the Java compiler inserts code to acquire the lock before executing the body of the synchronized method and code to release the lock before the method returns.

Access to an object may also be made mutually exclusive by using the synchronized statement. For example, an alternative (but less elegant) way to correct the example would be to modify the Turnstile.run() method:

public void run() {

while(true)

synchronized(people_){

people_.increment();

}

}

Previous slide Next slide Back to the first slide View Graphic Version