9am

Synchronized Blocking Queue

In Uncategorized on November 14, 2010 at 10:03 am

Synchronization can be solved using intrinsic locks, explicit locking or optimistic locking with Compare-And-Swap (CAS) logic.

This implementation uses notifyAll() which can be avoided using Java’s new Lock and Condition objects.
NotifyAll is needed for the implementation to work correctly but the down side is that more threads than necessary are signalled when state changes.

This post deals with a rudimentary in-efficient way of synchronization :

package self.synchronization;

public class BlockingQueue1<T> {

private Node head = null;
private Node tail = null;

private final int maxCount = 10;

private volatile int currentCount = 0;

public void produce(T item) throws InterruptedException

{

Node newTail = new Node(item, null);

synchronized(this)

{

// condition

while (this.currentCount >= maxCount)

{

this.wait();

}

 

if (tail != null)

{

tail.next = newTail;

}

else

{

tail = newTail;

head = newTail;

}

 

++this.currentCount;

this.notifyAll();

}

}

public T consume() throws InterruptedException

{

Node returnNode = null;

synchronized(this)

{

// condition

while (currentCount == 0)

{

this.wait();

}

returnNode = head;

head = head.next;

if (head == null) tail = null;

–currentCount;

this.notifyAll();

}

return returnNode.item;

}

private class Node

{

public final T item;

public Node next;

Node(T item, Node next)

{

this.item = item;

this.next = next;

}

}

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: