package otherSupport.bufferControl;


import java.nio.ByteBuffer;


public class DirectByteBufferControlTest {

	public static void main(String[] args) {

		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) { }		
		
		int n = 5000;
		int nThreads = 10;
		ByteBuffer buf[] = new ByteBuffer[n];
		
		Allocer alloc[] = new Allocer[nThreads];
		Thread thread[] = new Thread[nThreads];
		
		for(int i=0; i < nThreads; i++){
			alloc[i] = new Allocer(buf, i, nThreads);
			thread[i] = new Thread(alloc[i]);
			thread[i].start();
		
			try {
				Thread.sleep(150);
			} catch (InterruptedException e) { }			
		}
		
		/*try {
			Thread.sleep(5000);
		} catch (InterruptedException e) { }

		for(int i=0; i < nThreads; i++){
			alloc[i].canDealloc = true;
		}//*/		
		
		while(true){
			System.out.println(DirectBufferControl.getUsedMemory() + " / " + DirectBufferControl.getMaxMemory() + ", nA = " + Allocer.allocs + ", nD = " + Allocer.deallocs);
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) { }	
		}
				
	}
	
	public static class Allocer implements Runnable {
		public static int allocs = 0;
		public static int deallocs = 0;
		public static String merp = "rar";
		
		ByteBuffer buf[];
		int start; 
		int skip;
		public boolean canDealloc = true;
		
		public Allocer(ByteBuffer buf[], int start, int skip) {
			this.buf = buf;
			this.start = start;
			this.skip = skip;
		}
		@Override
		public void run() {
			int i=-1;
			try{
				for(i=start; i < buf.length; i+=skip){
					buf[i] = DirectBufferControl.allocateDirect(10000000); //1MB					
					allocs++;
					if( ((i/skip) % 10) == 0)
						System.out.println(start + ": Alloc " + i); 
				}
			}catch(OutOfMemoryError err){
				System.out.println(start + ": OOM at " + i);
			}
			
			while(!canDealloc){
				try {
					Thread.sleep(10);
				} catch (InterruptedException e) { }
			}
			
			for(i=start; i < buf.length; i+=skip){
				if(buf[i] != null){
					DirectBufferControl.freeBuffer(buf[i]);
					deallocs++;
				}
				if( ((i/skip) % 10) == 0)
					System.out.println(start + ": Dealloc" + i); 
			}
		}
	}
	
}
