package com.hammurapi.common.concurrent.tests;

import java.util.Collection;
import java.util.Random;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import junit.framework.Assert;

import org.junit.Test;

import com.hammurapi.common.concurrent.NonQueueingThreadPoolExecutorService;

public class NonQueuingThreadPoolExecutorServiceTest {
	
	class TestRunnable implements Runnable {
		
		private int id;
		private Collection<String> collector;
		private long delay;

		public TestRunnable(int id, long delay, Collection<String> collector) {
			this.id = id;
			this.collector = collector;
			this.delay = delay;
		}

		@Override
		public void run() {		
			collector.add(this.toString());
			try {
				Thread.sleep(delay);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		@Override
		public String toString() {
			return id + " " + Thread.currentThread();
		}
		
	}
	
	@Test
	public void test() throws Exception {
		NonQueueingThreadPoolExecutorService es = new NonQueueingThreadPoolExecutorService(Executors.defaultThreadFactory(), 5);
		Collection<String> collector = new ConcurrentLinkedQueue<String>();
		int numberOfTasks = 200;
		Random random = new Random(System.currentTimeMillis());
		for (int i=0; i<numberOfTasks; ++i) {
			es.execute(new TestRunnable(i, random.nextInt(200), collector));
//			Thread.sleep(10);
		}
		es.shutdown();
		es.awaitTermination(0, TimeUnit.MILLISECONDS);
		for (String msg: collector) {
			System.out.println("*** "+msg);
		}
		Assert.assertEquals(numberOfTasks, collector.size());
	}

}
