package rabbit.io;

import java.nio.ByteBuffer;

/** A handle to a ByteBuffer that uses a buffer handler
 *
 * @author <a href="mailto:robo@khelekore.org">Robert Olofsson</a>
 */
public class CacheBufferHandle implements BufferHandle {
    private final BufferHandler bh;
    private ByteBuffer buffer;
    private boolean mayBeFlushed = true;

    /** Create a new CacheBufferHandle that uses the given BufferHandler
     *  for the caching of the ByteBuffer:s
     * @param bh the BufferHandler that is the actual cache
     */
    public CacheBufferHandle (BufferHandler bh) {
	this.bh = bh;
    }

    public boolean isEmpty () {
	return buffer == null || !buffer.hasRemaining ();
    }
    
    public ByteBuffer getBuffer () {
	if (buffer == null)
	    buffer = bh.getBuffer ();
	return buffer;
    }
    
    public ByteBuffer getLargeBuffer () {
	buffer = bh.growBuffer (buffer);
	return buffer;
    }

    public boolean isLarge (ByteBuffer buffer) {
	return bh.isLarge (buffer);
    }

    public void possiblyFlush () {
	if (!mayBeFlushed)
	    throw new IllegalStateException ("buffer may not be flushed!: " +
					     System.identityHashCode (buffer));
	if (buffer == null)
	    return;
	if (!buffer.hasRemaining ()) {
	    bh.putBuffer (buffer);
	    buffer = null;
	}
    }

    public void setMayBeFlushed (boolean mayBeFlushed) {
	this.mayBeFlushed = mayBeFlushed;
    }

    @Override public String toString () {
	return getClass ().getName () + "[buffer: " + buffer + 
	    ", bh: " + bh + "}";
    }
}

@@ -598,32 +598,45 @@
   %7D%0A%0A    public 
+synchronized 
 boolean isEmpty 
@@ -636,24 +636,24 @@
 sEmpty () %7B%0A
-
 %09return buff
@@ -705,32 +705,45 @@
     %0A    public 
+synchronized 
 ByteBuffer getBu
@@ -842,16 +842,29 @@
  public 
+synchronized 
 ByteBuff
@@ -1035,24 +1035,37 @@
 %0A    public 
+synchronized 
 void possibl
@@ -1328,32 +1328,32 @@
 null;%0A%09%7D%0A    %7D%0A%0A
-
     public void 
@@ -1347,16 +1347,29 @@
  public 
+synchronized 
 void set

Synchronize access to the buffer.