
Untitled
By: a guest on
Aug 11th, 2012 | syntax:
None | size: 1.10 KB | hits: 4 | expires: Never
synchronized methods in a Runnable
public class Packer implements Runnable {
private BlockingQueue<byte[]> msgQueue;
private Object lock = new Object();
private Packet packet;
private boolean running = false;
public synchronized void append(byte[] payload) throws InterruptedException {
msgQueue.put(payload);
}
public synchronized void setPacketCapacity(int size) {
synchronized (lock) {
// check to see if we need to flush the current packet first, etc.
packet.setCapacity(size);
}
}
public void run() {
running = true;
while (running) {
try {
byte[] msg = msgQueue.take();
synchronized (lock) {
packet.add(msg);
// check if we need to flush the packet, etc.
}
} catch (InterruptedException ex) {
logger.warn("interrupted");
running = false;
} catch (Exception e) {
logger.error(e);
}
}
logger.warn("stop");
}
}