by Uwe B. Meding
Mutex objects and/or semaphores are use to manage resource access contention. In Java, the standard is to use the synchronized
guards around critical pieces of code, to make sure that only specific threads can access a resource. One of the issues with these guards is that they are very local and promote a programming structure that force the implementation of choke points. These points represent a well-defined point at which all transactions with a resource are funneled. In large multi-hosted systems, points like this become a scaling and performance problem.
In this blog I am showing how to design re-entrant mutex objects in Java, which allow resource management over a much larger system infrastructure. For example, stateless application servers, can now hold a lock across a set of independent calls. A downloadable version is at the end of this article.
The basic functionality is to use the current active thread to manage the lock and create a “revolving” platform for the owners of a lock. The following snippet waits (possibly indefinitely) for a lock to become available:
synchronized (this) { |
This snippet waits for some time to acquire a lock. For this we use the expiring wait
method. This will guarantee that we are not waiting indefinitely for a resource to become available:
synchronized (this) {
|
Thread thread = Thread.currentThread(); |
Here are links to downloadable versions of this code.
Leave a Reply
You must be logged in to post a comment.