Wednesday, November 22, 2006

Java 5 Concurrency: Selecting Locks

As with synchronizers, there is a choice of a few implementations of Locks in Java 5. In the previous post (selecting synchronizers), I gathered a few usage scenarios where the different synchronizers may be used. In this post, I will put together a few usage scenarios where the different Lock implementations may be used.
  • Lock: Lock implementations provide more extensive locking operations than can be obtained using synchronized methods and statements. The standard lock implementation may be used anywhere there is a need to restrict access to a shared resource so that only one thread of execution may access the resource. Spceifically,
    • When acquiring and releasing a lock may happen in different lexical scopes.
    • Chain locking: you acquire the lock of node A, then node B, then release A and acquire C, then release B and acquire D and so on ...
  • Read/Write Lock: maintains a pair of associated locks, one for read-only operations and one for writing. The read lock may be held simultaneously by multiple reader threads, so long as there are no writers. The write lock is exclusive.Usage Scenarios:
    • In scenarios where where is high frequency of reads and the duration of each is sufficiently long. User registries have such a data access pattern.
It should be noted that the standard lock may be used in any place a ReadWriteLock is used, but the performance gains by using a ReadWriteLock will be high when used in the proper application. Only profiling and measurement will establish whether the use of a read-write lock is suitable for your application.

No comments:

Post a Comment

Popular Posts