Monitors in Java
Monitors in Java
Any object may be a monitor in Java by making all its methods synchronized and its data atttributes private or protected. Conseqently, the data encapsulated by the object can only be accessed via its methods. Because this access is synchronized, mutual exclusion is enforced.
class Counter {
private long value_ = 0;
public synchronized void inc() { ++value_;}
public synchronized void dec() { --value_;}
public synchronized long value() { return(value_);}
}
Note: Java guarantees atomic access to datatypes which require 32bits or less.
long is a 64 bit quantity and consequently atomic access is not guaranteed.