Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Aug 11th, 2012  |  syntax: None  |  size: 1.10 KB  |  hits: 4  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. synchronized methods in a Runnable
  2. public class Packer implements Runnable {
  3.     private BlockingQueue<byte[]> msgQueue;
  4.     private Object lock = new Object();
  5.     private Packet packet;
  6.     private boolean running = false;
  7.  
  8.     public synchronized void append(byte[] payload) throws InterruptedException {
  9.         msgQueue.put(payload);
  10.     }
  11.  
  12.     public synchronized void setPacketCapacity(int size) {
  13.         synchronized (lock) {
  14.             // check to see if we need to flush the current packet first, etc.
  15.             packet.setCapacity(size);
  16.         }
  17.     }
  18.     public void run() {
  19.         running = true;
  20.         while (running) {
  21.             try {
  22.                 byte[] msg = msgQueue.take();
  23.                 synchronized (lock) {
  24.                     packet.add(msg);
  25.                     // check if we need to flush the packet, etc.
  26.                 }
  27.             } catch (InterruptedException ex) {
  28.                 logger.warn("interrupted");
  29.                 running = false;
  30.             } catch (Exception e) {
  31.                 logger.error(e);
  32.             }
  33.         }
  34.         logger.warn("stop");
  35.     }
  36. }