Java Synch
Java Synch
Java Synchronization Java uses the concept of monitors Java uses the concept that every object has a lock
synchronized Statement
Calling a synchronized method attempts to possess the lock If no one owns the lock, then this thread has/owns the lock.
If a calling thread does not own the lock (another thread already owns it), the calling thread is placed in the entry set for the objects lock.
Entry Set
return item;
}
Multiple Notifications
notify() selects an arbitrary thread from the wait set. *This may not be the thread that you want to be selected.
Java does not allow you to specify the thread to be selected. notifyAll() removes ALL threads from the wait set and places them in the entry set. This allows the threads to decide among themselves who should proceed next. notifyAll() is a conservative strategy that works best when multiple threads may be in the wait set.
startRead() Method
public synchronized int startRead() {
while (dbWriting == true) { try { wait(); } catch (InterruptedException e) { } } ++readerCount; if (readerCount == 1) dbReading = true; return readerCount; }
endRead() Method
Writer Methods
public void startWrite() {
while (dbReading == true || dbWriting == true) try { wait(); } catch (InterruptedException e) { } dbWriting = true; } public void endWrite() { dbWriting = false; notifyAll();
Block Synchronization
This yields a lock scope that is typically smaller than a synchronized method.
// non-critical section
}
2 types of monitors
Signal-and-continue Monitor Monitor that allows a thread to signal that the monitor is available, but does NOT require the thread (signaler) to release the lock until it exits the monitor, at which point a signaled thread may enter the monitor. (used by Java) Signal-and-exit Monitor Monitor that requires a thread to release the lock on the monitor as soon as the thread signals another thread. (signaler immediately leaves, then the signaled thread comes in.)
Java Semaphores
Java does not provide a semaphore, but a basic semaphore can be constructed using Java synchronization mechanism.
Semaphore Class
public Semaphore(int v) {
value = v; } public synchronized void P() { /* see next slide */ }
P() Operation
value --;
}
V() Operation
notify(); }