Byte FIFO : Lock Synchronize « Threads « Java






Byte FIFO

Byte FIFO
     
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class ByteFIFOTest extends Object {
  private ByteFIFO fifo;
  private byte[] srcData;

  public ByteFIFOTest() throws IOException {
    fifo = new ByteFIFO(20);

    makeSrcData();
    System.out.println("srcData.length=" + srcData.length);

    Runnable srcRunnable = new Runnable() {
        public void run() {
          src();
        }
      };
    Thread srcThread = new Thread(srcRunnable);
    srcThread.start();

    Runnable dstRunnable = new Runnable() {
        public void run() {
          dst();
        }
      };
    Thread dstThread = new Thread(dstRunnable);
    dstThread.start();
  }

  private void makeSrcData() throws IOException {
    String[] list = {
        "The first string is right here",
        "The second string is a bit longer and also right here",
        "The third string",
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
        "0123456789",
        "The last string in the list"
      };

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(list);
    oos.flush();
    oos.close();
    
    srcData = baos.toByteArray();
  }

  private void src() {
    try {
      boolean justAddOne = true;
      int count = 0;

      while ( count < srcData.length ) {
        if ( !justAddOne ) {
          int writeSize = (int) ( 40.0 * Math.random() );
          writeSize = Math.min(writeSize, srcData.length - count);

          byte[] buf = new byte[writeSize];
          System.arraycopy(srcData, count, buf, 0, writeSize);
          fifo.add(buf);
          count += writeSize;

          System.out.println("just added " + writeSize + " bytes");
        } else {
          fifo.add(srcData[count]);
          count++;

          System.out.println("just added exactly 1 byte");
        }

        justAddOne = !justAddOne;
      }
    } catch ( InterruptedException x ) {
      x.printStackTrace();
    }
  }

  private void dst() {
    try {
      boolean justAddOne = true;
      int count = 0;
      byte[] dstData = new byte[srcData.length];

      while ( count < dstData.length ) {
        if ( !justAddOne ) {
          byte[] buf = fifo.removeAll();
          if ( buf.length > 0 ) {
            System.arraycopy(buf, 0, dstData, count, buf.length);
            count += buf.length;
          }

          System.out.println(
            "just removed " + buf.length + " bytes");
        } else {
          byte b = fifo.remove();
          dstData[count] = b;
          count++;

          System.out.println(
            "just removed exactly 1 byte");
        }

        justAddOne = !justAddOne;
      }

      System.out.println("received all data, count=" + count);

      ObjectInputStream ois = new ObjectInputStream(
          new ByteArrayInputStream(dstData));

      String[] line = (String[]) ois.readObject();

      for ( int i = 0; i < line.length; i++ ) {
        System.out.println("line[" + i + "]=" + line[i]);
      }
    } catch ( ClassNotFoundException x1 ) {
      x1.printStackTrace();
    } catch ( IOException iox ) {
      iox.printStackTrace();
    } catch ( InterruptedException x ) {
      x.printStackTrace();
    }
  }

  public static void main(String[] args) {
    try {
      new ByteFIFOTest();
    } catch ( IOException iox ) {
      iox.printStackTrace();
    }
  }
}
class ByteFIFO extends Object {
  private byte[] queue;
  private int capacity;
  private int size;
  private int head;
  private int tail;

  public ByteFIFO(int cap) {
    capacity = ( cap > 0 ) ? cap : 1; // at least 1
    queue = new byte[capacity];
    head = 0;
    tail = 0;
    size = 0;
  }

  public int getCapacity() {
    return capacity;
  }

  public synchronized int getSize() {
    return size;
  }

  public synchronized boolean isEmpty() {
    return ( size == 0 );
  }

  public synchronized boolean isFull() {
    return ( size == capacity );
  }

  public synchronized void add(byte b) 
      throws InterruptedException {

    waitWhileFull();

    queue[head] = b;
    head = ( head + 1 ) % capacity;
    size++;

    notifyAll(); // let any waiting threads know about change
  }

  public synchronized void add(byte[] list) 
      throws InterruptedException {

    // For efficiency, the bytes are copied in blocks
    // instead of one at a time. As space becomes available,
    // more bytes are copied until all of them have been
    // added.

    int ptr = 0;

    while ( ptr < list.length ) {
      // If full, the lock will be released to allow 
      // another thread to come in and remove bytes.
      waitWhileFull();

      int space = capacity - size;
      int distToEnd = capacity - head;
      int blockLen = Math.min(space, distToEnd);

      int bytesRemaining = list.length - ptr;
      int copyLen = Math.min(blockLen, bytesRemaining);

      System.arraycopy(list, ptr, queue, head, copyLen);
      head = ( head + copyLen ) % capacity;
      size += copyLen;
      ptr += copyLen;

      // Keep the lock, but let any waiting threads 
      // know that something has changed.
      notifyAll();
    }
  }

  public synchronized byte remove() 
      throws InterruptedException {

    waitWhileEmpty();
    
    byte b = queue[tail];
    tail = ( tail + 1 ) % capacity;
    size--;

    notifyAll(); // let any waiting threads know about change

    return b;
  }

  public synchronized byte[] removeAll() {
    // For efficiency, the bytes are copied in blocks
    // instead of one at a time. 

    if ( isEmpty() ) {
      // Nothing to remove, return a zero-length
      // array and do not bother with notification
      // since nothing was removed.
      return new byte[0]; 
    }

    // based on the current size
    byte[] list = new byte[size]; 

    // copy in the block from tail to the end
    int distToEnd = capacity - tail;
    int copyLen = Math.min(size, distToEnd);
    System.arraycopy(queue, tail, list, 0, copyLen);

    // If data wraps around, copy the remaining data
    // from the front of the array.
    if ( size > copyLen ) {
      System.arraycopy(
          queue, 0, list, copyLen, size - copyLen);
    }

    tail = ( tail + size ) % capacity;
    size = 0; // everything has been removed

    // Signal any and all waiting threads that 
    // something has changed.
    notifyAll(); 

    return list; 
  }

  public synchronized byte[] removeAtLeastOne() 
      throws InterruptedException {

    waitWhileEmpty(); // wait for a least one to be in FIFO
    return removeAll();
  }

  public synchronized boolean waitUntilEmpty(long msTimeout) 
      throws InterruptedException {

    if ( msTimeout == 0L ) {
      waitUntilEmpty();  // use other method
      return true;
    }

    // wait only for the specified amount of time
    long endTime = System.currentTimeMillis() + msTimeout;
    long msRemaining = msTimeout;

    while ( !isEmpty() && ( msRemaining > 0L ) ) {
      wait(msRemaining);
      msRemaining = endTime - System.currentTimeMillis();
    }

    // May have timed out, or may have met condition, 
    // calc return value.
    return isEmpty();
  }

  public synchronized void waitUntilEmpty() 
      throws InterruptedException {

    while ( !isEmpty() ) {
      wait();
    }
  }

  public synchronized void waitWhileEmpty() 
      throws InterruptedException {

    while ( isEmpty() ) {
      wait();
    }
  }

  public synchronized void waitUntilFull() 
      throws InterruptedException {

    while ( !isFull() ) {
      wait();
    }
  }

  public synchronized void waitWhileFull() 
      throws InterruptedException {

    while ( isFull() ) {
      wait();
    }
  }
}


           
         
    
    
    
    
  








Related examples in the same category

1.Thread: Dining Philosophers
2.Synchronizing on another objectSynchronizing on another object
3.Operations that may seem safe are not, when threads are presentOperations that may seem safe are not, when threads are present
4.Synchronizing blocks instead of entire methodsSynchronizing blocks instead of entire methods
5.Boolean lockBoolean lock
6.Static synchronized blockStatic synchronized block
7.Thread notifyThread notify
8.Thread deadlockThread deadlock
9.Synchronize methodSynchronize method
10.Threads joinThreads join
11.Static synchronizeStatic synchronize
12.No synchronizeNo synchronize
13.Thread synchronizationThread synchronization
14.Synchronized Block demoSynchronized Block demo
15.Interruptible Synchronized Block Interruptible Synchronized Block
16.SignalingSignaling
17.Simple Object FIFOSimple Object FIFO
18.Object FIFOObject FIFO
19.Daemon Lock
20.Determining If the Current Thread Is Holding a Synchronized Lock
21.Handle concurrent read/write: use synchronized to lock the data
22.Lock for read and write
23.Read Write Lock
24.Coordinates threads for multi-threaded operations
25.A reader-writer lock from "Java Threads" by Scott Oak and Henry Wong.
26.Invoke a series of runnables as closely to synchronously as possible
27.This program shows how multiple threads can safely access a data structure, using synchronized methods
28.This program shows data corruption when multiple threads access a data structure.
29.Stores a single object for the producer/consumer pattern and takes care of thread synchronization.
30.The BooleanLock class provides a useful encapsulation of a boolean variable that is easily and safely accessed from multiple theads.