Java Reference
In-Depth Information
A new package, java.util.concurrent.locks , has been created in JDK 5, which provides
some benefits to SCJD candidates, including the ability to have a ReadWriteLock (where multi-
ple threads could all lock a record for reading, but only one thread could lock the record for
writing—this will improve concurrency). We will examine ReadWriteLock s in the section dis-
cussing the DvdFileAccess class in Chapter 5.
In JDK 1.4, after returning from a call to wait(milliseconds) , it was not possible to
know directly whether the thread had been notified, or whether the timeout had elapsed. The
Lock.tryLock(time, unit) method returns a boolean indicating whether it had gained the lock
or whether the time expired. An example of using the similar Lock.await(time, unit) method
is shown in the “Creating Our Logical Reserve Methods” section in Chapter 5. And while this
technique is not required for the SCJD assignment, it is now possible to set multiple condi-
tions upon which a thread might be notified.
Although the new lock code looks different from using synchronized blocks, it is not too
difficult to convert code from one style to another. For example, the following code uses a syn-
chronized block:
Object lock = new Object();
public void doSomething() {
synchronized (lock) {
while (true) {
try {
lock.wait();
// something happens here
} catch (InterruptedException ie) {
// handle exception
}
}
}
}
This code can be changed to the new format like this:
private static Lock lock = new ReentrantLock();
private static Condition lockReleased = lock.newCondition();
public void doSomething() {
lock.lock();
try {
while (true) {
lockReleased.await();
// something happens here
}
} catch (InterruptedException ie) {
// handle exception
} finally {
lock.unlock();
}
}
Search WWH ::




Custom Search