Last active
October 4, 2016 23:48
-
-
Save hackjutsu/22d982c602c798d48112839e6b3354ec to your computer and use it in GitHub Desktop.
Sample code for thread safe blocking queue in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ArrBlockingQueue { | |
final private Lock _lock = new ReentrantLock(); | |
final private Condition _notFull = _lock.newCondition(); | |
final private Condition _notEmpty = _lock.newCondition(); | |
final private Object[] _items; | |
private int _putptr, _takeptr, _count; | |
public ArrBlockingQueue(final int size) { | |
// Assuming size is valid here | |
_items = new Object[size]; | |
} | |
public void put(final Object x) throws InterruptedException { | |
_lock.lock(); | |
try { | |
while (_count == _items.length) | |
_notFull.await(); | |
_items[_putptr] = x; | |
if (++_putptr == _items.length) _putptr = 0; | |
++_count; | |
_notEmpty.signalAll(); | |
} finally { | |
_lock.unlock(); | |
} | |
} | |
public Object take() throws InterruptedException { | |
_lock.lock(); | |
try { | |
while (_count == 0) | |
_notEmpty.await(); | |
Object x = _items[_takeptr]; | |
if (++_takeptr == _items.length) _takeptr = 0; | |
--_count; | |
_notFull.signalAll(); | |
return x; | |
} finally { | |
_lock.unlock(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment