Home  Synchronization and concurrency  wait/notify  final  volatile  synchronized keyword  Java threading  Deadlock (and avoiding it)  Java 5: ConcurrentHashMap  Atomic variables  Explicit locks  Queues  Semaphores  CountDownLatch  CyclicBarrier

Explicit locks in Java 5 (ctd)

Java 5 introduces classes that implement explicit locks. Explicit locks are useful in cases where you need to overcome some of the shortcomings of built-in synchronization. In particular, they have the following features:

  • A thread can attempt to acquire a lock interruptibly;
  • A thread can give a timeout value for attempting to acquire the lock;
  • Read/write locks are supported– that is, locks that allow multiple concurrent readers if the lock is not locked for writing;
  • The traditional wait/notify metaphor is extended to allow conditions (see below);
  • Support for fairness (if more than one thread is waiting for a lock, they acquire in first-in-first-out order when it becomes available);
  • The ability to lock beyond the scope of a block: for example, one method can pass a lock object to another thread;
  • Locks can be queried to find out, for example, if they currently have any threads waiting to acquire them.

The package java.util.concurrent.locks contains the various lock classes and interfaces. The most significant of these to most applications are three interfaces: Lock, ReadWriteLock, and Condition, plus the two lock implementations ReentrantLock and ReentrantReadWriteLock. (The package also contains a few other abstract classes that are useful if you are implementing a new lock type; we won't look at those here.)

On the next page, we look at an example of using a Java 5 Lock instance.

Article written by Neil Coffey (@BitterCoffey).

Software

 LetterMeister (word puzzle game for iPhone)
 Currency Quoter (currency converter/predictor)
 French Vocab Games for iPhone/iPad
 Vocabularium: create Spanish vocab podcasts


Java programming articles and tutorials on this site are written by Neil Coffey (@BitterCoffey). Suggestions are always welcome if you wish to suggest topics for Java tutorials or programming articles, or if you simply have a programming question that you would like to see answered on this site. Most topics will be considered. But in particular, the site aims to provide tutorials and information on topics that aren't well covered elsewhere, or on Java performance information that is poorly described or understood. Suggestions may be made via the Javamex blog (see the site's front page for details).
Copyright © Neil Coffey 2015. All rights reserved.