package com.eactive.eai.adapter.socket2.filter.executor;

import java.util.concurrent.*;



public class BlockingThreadPoolExecutor extends ThreadPoolExecutor {
	private Semaphore semaphore;
        
    public BlockingThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime,
			TimeUnit unit, BlockingQueue workQueue) {
		super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
		this.semaphore = new Semaphore(maximumPoolSize);
	}

    @Override
    public void execute(final Runnable task) {
        try {
            semaphore.acquire();
            super.execute(new Runnable() {
            	public void run() {
	            	try {
	            		task.run();
	            	} finally {
	            		semaphore.release();
	            	}
            	}
            });
        } catch (InterruptedException e) {
        	throw new RuntimeException(e.getMessage(), e);
        } catch(RejectedExecutionException e) {
            semaphore.release();
            throw e;
        }
    }
}