Concurrent Programming

Blocking Queue

Behavior

Quite often in threaded applications we have a producer-consumer situation where some threads want to add jobs onto a queue, and some other worker threads want to remove jobs from the queue and then execute them. It is quite useful in such circumstances to write a queue which blocks on pop when there is nothing on the queue. Otherwise the consumers would have to poll, and polling is not very good because it wastes CPU cycles. When clients attempt to retrieve elements but none are available, a BlockingQueue encapsulates code that waits until an element becomes available.

Usage

The server runs infinitely, accepting requests from a client. Clients can send requests asynchronously and rapidly—the server only adds a client request to the server’s queue (ie. blocking queue), then returns immediately to the client. A separate server thread loops indefinitely, asking the BlockingQueue to return when a new request becomes available. Once a request is available, it’s removed from the queue. The server then handles the request.

Reference

  1. Java Specialist – Blocking Queue

 

ReentrantLock

Behavior

ReentrantLock supports all of the lock-acquisition modes defined by Lock, providing more flexibility for dealing with lock unavailability than does synchronized. Intrinsic locking (ie. synchronized) works fine in most situations but has some functional limitations: It is not possible to interrupt a thread waiting to acquire a lock. If you want the lock, you need to prepare to wait for it forever. Using ReentrantLock, you have more flexibility and scalability:

  1. Timed and Polled lock acquisition – Use tryLock(). One form of this method returns immediately if the lock is already held and the other can wait for some period of time for the lock to become available before giving up. In both cases, we could effectively loop and retry the tryLock() until it succeeds.
  2. Interruptable lock acquisition – Use lockInterruptabily() allows locking to be used within cancellable activities
  3. Non-block structured locking

Usage

Reference

  1. Choosing between synchronized and ReentrantLock
  2. More flexible, scalable locking in JDK 5 – Brian Goetz

 


Comments

comments

Subscribe

Subscribe my "7 Days Crack Course" to make money online together! Free for the first 100 registration.

No comments yet.

Leave a Reply