Thread Pool , Executors ...

Sorry if i make a stupid post now, but i'm looking for a implementation of a Thread Pool using the latest 1.5 java.util.concurrent classes and i can't find anything serious. Any implementation or link to a tutorial should be vary helpful.
Thnx

but i'm looking
for a implementation of a Thread Pool using
the latest 1.5 java.util.concurrent classes and i
can't find anything serious. Any implementation or
link to a tutorial should be vary helpful.
Thnxhere is an Example :
import java.util.concurrent.*;
public class UtilConcurrentTest {
public static void main(String[] args) throws InterruptedException {
int numThreads = 4;
int numTasks = 20;
ExecutorService service = Executors.newFixedThreadPool(numThreads);
// do some tasks:
for (int i = 0; i < numTasks; i++) {
service.execute(new Task(i));
service.shutdown();
log("called shutdown()");
boolean isTerminated = service.awaitTermination(60, TimeUnit.SECONDS);
log("service terminated: " + isTerminated);
public static void log(String msg) {
System.out.println(System.currentTimeMillis() + "\t" + msg);
private static class Task implements Runnable {
private final int id;
public Task(int id) {
this.id = id;
public void run() {
log("begin:\t" + this);
try { Thread.sleep(1000); } catch (InterruptedException e) {}
log("end\t" + this);
public String toString() {
return "Task " + id + " in thread " + Thread.currentThread().getName();
}

Similar Messages

  • Thread pool executor problem

    When using a thread pool executor (java.util.concurrent.ThreadPoolExecutor) to limit the number of threads executing at a time, the number of threads running still exceeds the limit number.
    This is the code:
    private ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 3, 20, TimeUnit.SECONDS, new LinkedBlockingQueue());
    The number of tasks in my program are 4, so i always have 4 threads running, although i limited it to 3.
    Can anyone help me with this problem? Or can u propose another solution to limit the number of running threads? By the way, i also tried using a newFixedThreadPool() and got the same problem.
    Thx.

    The number of tasks in my program are 4, so i always
    have 4 threads running, although i limited it to 3.How do you know that there are 4 threads running? If you're generating a JVM thread dump, you're going to see threads that are used internally by the JVM.
    Here's a simple program that creates a fixed-size threadpool and runs jobs. It limits the number of concurrent threads to 3. Compare it to what you're doing, I'm sure that you'll find something different. Also, verify that you're not creating threads somewhere else in your program; all of the ThreadPoolExecutor threads will have names of the form "pool-X-thread-Y"
    import java.util.concurrent.Executors;
    import java.util.concurrent.ExecutorService;
    public class ThreadPoolTest {
        public static void main(String[] args) {
            ExecutorService pool = Executors.newFixedThreadPool(3);
            for (int ii = 0 ; ii < 10 ; ii++) {
                pool.execute(new MyRunnable());
            pool.shutdown();
        private static class MyRunnable implements Runnable {
            public void run() {
                log("running");
                try {
                    Thread.sleep(1000L);
                catch (InterruptedException e) {
                    log("interrupted");
            private void log(String msg) {
                System.err.println(
                        msg + " on " + Thread.currentThread().getName()
                        + " at " + System.currentTimeMillis());
    }

  • Thread Pool executor

    I run a set of java programs as a single process in solaris os. Those java programs make use of thread pool executor to process threads and it runs in an infinite loop for ever. Thread processing is done whenever data is populated in database from an external source. The issue is after 2 to 3 days of running the process, it gets slowed down in executing the threads and finally it stops executing. What may be the reason for this.....how to solve this......... or how to fine tune thread pool executor in java or how to make best use of it...........

    Hey folks.... Sorry its a typo in my e-mail. Sorry about that. I am pasting the actual code here.
    The problem again is that in the index function only FirstRunnable executes but not the SecondRunnable
    final public class Crawler {
        / create an instance of the ISSThreadPoolExecutor /
        private static ThreadPoolExecutor mythreadpoolexecutor = ThreadPoolExecutor.getInstance();
        / Constructor /
        / Index function /
        public void index( .... ) {
            :::::: code :::::::::
            // Execute this folder in a seperate thread.
            this.issthreadpoolexecutor.execute(new FirstRunnable(alpha, beta, gamma));
        / The Inner Class /
        class FirstRunnable implements Runnable {
            public FirstRunnable(int alpha, int beta, int gamma) {
            public void run() {
                            doSomething();
                            // Some other tasks and ...spawn of another thread.
                            issthreadpoolexecutor.execute(new SecondRunnable(a));
             // The Inner Class that Indexes the Folder
              class SecondRunnable implements Runnable {
                      private int ei;
                      public SecondRunnable ( int abc ) {
                            this.ei = abc;
                      public void run() {
                            doSomething ( ".....") ;
              } // End of SecondRunnable Class.
         } // End of FirstRunnable class.
    } // End of Crawler Class.

  • Optimization of Thread Pool Executor

    Hi,
    I am using ThreadPoolexecutor by replacing it with legacy Thread.
    I have created executor as below:
    pool = new ThreadPoolExecutor(coreSize, size, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(coreSize), new CustomThreadFactory(name),new CustomRejectionExecutionHandler());
           pool.prestartAllCoreThreads();
    here core size is maxpoolsize/5
    and i have prestarted all the core threads on start up of application roughly around 160 threads.
    in legacy design we were creating and starting around 670 threads.
    But the point is even after using Executor and creating and replacing  legacy design we are not getting much better results.
    For results memory management we are using top command to see memory usage
    and for time we have placed loggers of System.currentTime in millis to check the usage.
    Please tell how to optimize this design
    Thanks & Regards,
    tushar

    The first step is to decide what you want to optimize. I'm guessing you want to minimize the total elapsed time for the job to run, but anyway that's your first step. Determine what you're optimizing. Then measure the performance of the job, with respect to that metric, for various pool sizes, and see what happens.
    However I'm not sure why you expected that rewriting the application to use the ThreadPoolExecutor would improve the runtime performance of the job. I would expect it might simplify the code and make it easier for future programmers to understand, but it's possible that your thread pool implementation performs just as well.

  • Thread Pool Executor ( Runnable Class Executing another Runnable Class )

    Hi Folks,
    I have my main class called ThreadPoolExecutorUser. I have two Runnable classes called XYZ and ABC
    in ThreadPoolExecutorUser class I execute the Runnable class XYZ. Which inturn executes Runnable class ABC.
    The problem is that the Runnable class ABC is never executed ?. Can some one please explain what I am I doing wrong.
    _RB
    More Description Below :
    *public class ThreadPoolExecutorUser {*
    ThreadPoolExecutor dude = new ThreadPoolExecutor (.... );
    // I Execute the firest Runnable Xyz here
    dude.execute ( XYZ );
    Now I have two Runnable inner Classes
    *Class XYZ extends Runnable {*
    public void run () {
    s.o.p ( " I am in Xyz Runnable " );
    dude.execute ( ABC );
    *class ABC extends Runnable {*
    public void run () {
    s.o.p ( " I am in ABC Runnable " );
    }

    Hey folks.... Sorry its a typo in my e-mail. Sorry about that. I am pasting the actual code here.
    The problem again is that in the index function only FirstRunnable executes but not the SecondRunnable
    final public class Crawler {
        / create an instance of the ISSThreadPoolExecutor /
        private static ThreadPoolExecutor mythreadpoolexecutor = ThreadPoolExecutor.getInstance();
        / Constructor /
        / Index function /
        public void index( .... ) {
            :::::: code :::::::::
            // Execute this folder in a seperate thread.
            this.issthreadpoolexecutor.execute(new FirstRunnable(alpha, beta, gamma));
        / The Inner Class /
        class FirstRunnable implements Runnable {
            public FirstRunnable(int alpha, int beta, int gamma) {
            public void run() {
                            doSomething();
                            // Some other tasks and ...spawn of another thread.
                            issthreadpoolexecutor.execute(new SecondRunnable(a));
             // The Inner Class that Indexes the Folder
              class SecondRunnable implements Runnable {
                      private int ei;
                      public SecondRunnable ( int abc ) {
                            this.ei = abc;
                      public void run() {
                            doSomething ( ".....") ;
              } // End of SecondRunnable Class.
         } // End of FirstRunnable class.
    } // End of Crawler Class.

  • Multiple thread pools under single executor

    I would like to segregate the tasks running in an Executor so that certain tasks (perhaps identified by an annotation) could be restricted to a thread pool of a limited size while others run in a different pool.
    The intend is to limit certain crunchy tasks so that they don't saturate a limited resource.
    As far as I can tell I can't do this with a ThreadPoolExecutor even with a custom ThreadFactory. The original Callable is wrapped a couple of times by the time the ThreadFactory.newThread method is called so I can't inspect it at that time. Also, once the maximumPoolSize is reached the waiting tasks will get handed off to whichever thread finishes first, thus making my fixed pools useless.
    I have a feeling that I will need to write my own ThreadPoolExecutor but I thought that I would ask if there was a way to do this with the existing classes first.
    Thanks.

    I used to do this.
    The problem comes in managing the work that flows between the queues, and managing the results. I need to be able to take the output from one task and feed it into another, potentially running in a different thread pool.
    Multiple queues mean waiting for more than one blocking event, which means multiple management threads with a meta-event queue feeding back to an dispatcher that does the messaging.
    With multiple management threads you have to poison all of those queues so that the thing shuts down when you are done.
    By the time that I'm done I may be better off just modifyingThreadPoolExecutor to do what I want. One work queue keeps the shutdown problem under control.
    Thanks for the feedback.

  • Creating Thread Pool with Executors.newFixedThreadPool(poolSize)

    I am creating a server socket and want a Thread pool to limit the number of threads created for serving each clients. I have written a code:
    private ExecutorService threadPool;
    //Creating a Thread Pool for handling new sessions
    threadPool=ThreadPool.createSessionThreadPool(poolSize);
    and in my main listen logic:
    serverSocket = new ServerSocket(listenPort);
    clientSocket = serverSocket.accept();
                        threadPool.execute(new Runnable(){
                             public void run(){
                                  handleConnection();
    and in handleConnection I am trying to read the inputstream in a while loop:
    public void handleConnection(){
    BufferedReader in=null;
    in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
    while (true) {
    if((fullCommandString = in.readLine()) ==null){
    wait(); // I assume that this wait will block the thread and keep the thread back in to the pool.
                        System.out.println(Thread.currentThread().getName() + " received the message");
                        System.out.println("echo: " + fullCommandString);
                        out.println("230 reply back \r\n");     
    why don't it keep the thread back in the pool when I call the wait() ? Is it since the thread is still active in reading the input stream? If so can any one hepl me with a snippet which will keep the thread back in the pool when there is noting on the input stream to read.

    Hi,
    The call to wait does not return the thread pool back to the pool. The thread will be associated with your runnable as long as your run method hasn't returned.
    It looks like you instead want to use NIO if you want to use a few threads to handle many clients.
    Kaj

  • A good design for a single thread pool manager using java.util.concurrent

    Hi,
    I am developing a client side project which in distinct subparts will execute some tasks in parallel.
    So, just to be logorroic, something like that:
    program\
                \--flow A\
                           \task A1
                           \task A2
                \--flow B\
                            \task B1
                            \task B2
                            \...I would like both flow A and flow B (and all their launched sub tasks) to be executed by the same thread pool, because I want to set a fixed amount of threads that my program can globally run.
    My idea would be something like:
    public class ThreadPoolManager {
        private static ExecutorService executor;
        private static final Object classLock = ThreadPoolManager.class;
         * Returns the single instance of the ExecutorService by means of
         * lazy-initialization
         * @return the single instance of ThreadPoolManager
        public static ExecutorService getExecutorService() {
            synchronized (classLock) {
                if (executor != null) {
                    return executor;
                } else {
                    // TODO: put the dimension of the FixedThreadPool in a property
                    executor = Executors.newFixedThreadPool(50);
                return executor;
         * Private constructor: deny creating a new object
        private ThreadPoolManager() {
    }The tasks I have to execute will be of type Callable, since I expect some results, so you see an ExecutorService interface above.
    The flaws with this design is that I don't prevent the use (for example) of executor.shutdownNow(), which would cause problems.
    The alternative solution I have in mind would be something like having ThreadPoolManager to be a Singleton which implements ExecutorService, implementing all the methods with Delegation to an ExecutorService object created when the ThreadPoolManager object is instantiated for the first time and returned to client:
    public class ThreadPoolManager implements ExecutorService {
        private static ThreadPoolManager pool;
        private static final Object classLock = ThreadPoolManager.class;
        private ExecutorService executor;
         * Returns the single instance of the ThreadPoolManager by means of
         * lazy-initialization
         * @return the single instance of ThreadPoolManager
        public static ExecutorService getThreadPoolManager() {
            synchronized (classLock) {
                if (pool !=null) {
                    return pool;
                } else {
                    // create the real thread pool
                    // TODO: put the dimension of the FixedThreadPool in a property
                    // file
                    pool = new ThreadPoolManager();
                    pool.executor = Executors.newFixedThreadPool(50);
                    // executor = Executors.newCachedThreadPool();
                    return pool;
         * Private constructor: deny creating a new object
        private ThreadPoolManager() {
        /* ======================================== */
        /* implement ExecutorService interface methods via delegation to executor
         * (forbidden method calls, like shutdownNow() , will be "ignored")
          // .....I hope to have expressed all the things, and hope to receive an answer that clarifies my doubts or gives me an hint for an alternative solution or an already made solution.
    ciao
    Alessio

    Two things. Firstly, it's better to use     private static final Object classLock = new Object();because that saves you worrying about whether any other code synchronises on it. Secondly, if you do decide to go for the delegation route then java.lang.reflect.Proxy may be a good way forward.

  • Thread pool throws reject exceptions even though the queue is not full

    Hi. I am using org.springframework.scheduling.concurrent.ThreadPo olTaskExecutor which is based on java
    java.util.concurrent.ThreadPoolExecutor
    with a enviornment under load.
    I see on some cases, that this thread pool throws tasks with reject exception
    even though the queue size is 0.
    According to the documentation, this thread pool should increase the pool size to core size and then wait untill all queue is full to create new threads.
    this is not what happends. for some reason the queue is not filled but exceptions are thrown.
    Any ideas why this can happen?

    This is the stack trace:
    taskExecutorStats-1 2010-04-27 11:01:43,324 ERROR [com.expand.expandview.infrastructure.task_executor] TaskExecutorController: RejectedExecutionException exception in thread: 18790970, failed on thread pool: [email protected]544f07, to run logic: com.expand.expandview.infrastructure.logics.DispatchLogicsProviderLogic
    org.springframework.core.task.TaskRejectedException: Executor [java.util.concurrent.ThreadPoolExecutor@dd9007] did not accept task: com.expand.expandview.infrastructure.task_executor.TaskExecuterController$1@141f728; nested exception is java.util.concurrent.RejectedExecutionException
         at org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor.execute(ThreadPoolTaskExecutor.java:305)
         at com.expand.expandview.infrastructure.task_executor.TaskExecuterController.operate(TaskExecuterController.java:68)
         at com.expand.expandview.infrastructure.proxies.DataProxy.callLogic(DataProxy.java:131)
         at com.expand.expandview.infrastructure.proxies.DataProxy.operate(DataProxy.java:109)
         at com.expand.expandview.infrastructure.logics.AbstractLogic.operate(AbstractLogic.java:455)
         at com.expand.expandview.server.app.logics.stats.StatsPersisterSingleChunkLogic.persistSlots(StatsPersisterSingleChunkLogic.java:362)
         at com.expand.expandview.server.app.logics.stats.StatsPersisterSingleChunkLogic.doLogic(StatsPersisterSingleChunkLogic.java:132)
         at com.expand.expandview.infrastructure.logics.AbstractLogic.execute(AbstractLogic.java:98)
         at com.expand.expandview.server.app.logics.ApplicationLogic.execute(ApplicationLogic.java:79)
         at com.expand.expandview.infrastructure.task_executor.TaskExecuterControllerDirect.operate(TaskExecuterControllerDirect.java:33)
         at com.expand.expandview.infrastructure.proxies.LogicProxy.service(LogicProxy.java:62)
         at com.expand.expandview.infrastructure.logics.AbstractLogic.service(AbstractLogic.java:477)
         at com.expand.expandview.server.app.logics.stats.StatsPersisterLogic.persist(StatsPersisterLogic.java:48)
         at com.expand.expandview.server.app.logics.stats.StatsPersisterLogic.doLogic(StatsPersisterLogic.java:19)
         at com.expand.expandview.infrastructure.logics.AbstractLogic.execute(AbstractLogic.java:98)
         at com.expand.expandview.server.app.logics.ApplicationLogic.execute(ApplicationLogic.java:79)
         at com.expand.expandview.infrastructure.task_executor.TaskExecuterController$1.run(TaskExecuterController.java:80)
         at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
         at java.lang.Thread.run(Thread.java:619)
    Caused by: java.util.concurrent.RejectedExecutionException
         at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:1760)
         at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:767)
         at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:658)
         at org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor.execute(ThreadPoolTaskExecutor.java:302)
         ... 19 more

  • Thread Pool Callback Mechanism

    I am using java.util.concurrent.ExecutorService to create a thread pool. I need a way to inform the user of the progress of the threads in the pool.
    Does anyone have any ideas of how to do this?

    I am using java.util.concurrent.ExecutorService to
    create a thread pool. I need a way to inform the user
    of the progress of the threads in the pool.
    Does anyone have any ideas of how to do this?Hand the Executor instances of SwingWorker, which implements RunnableFuture. SwingWorker also has a progress() method which can provide progress information.

  • The problem in the thread pool implemented by myself

    Hello, I need to a thread pool in J2ME CDC 1.0 + FP 1.0, so I implemented a simple one by myself that also meets my own requirement.
    Here is the main idea:
    The thread pool creates a fixed number of threads in advance. When a task comes, it is put in the waiting list. All threads tries to get the tasks from the waiting list. If no task exists, the threads wait until someone wakes them up.
    Here are the requirements from myself:
    1. when a task has finished its work in one execution, it is put in the waiting list for the next run.
    2. the task can control the delay between when the task owner tries to put it in the waiting list and when the task is actually put in the waiting list. I need this function because sometimes I don't want the tasks to run too often and want to save some CPU usage.
    In my program, I creates two thread pools. In one pool, every task don't use the delay, and the thread pool works very well. The other pool has the tasks that use the delay, and sometimes, as I can see from the printed information, there are many tasks in the waiting list but 0 or 1 thread executes tasks. It seems that the waiting threads cannot wake up when new tasks comes.
    I suspect the code in addTask(), but cannot find the reason why it fails. Could anyone please help me find out the bug in my code? I put the code of thread pool below
    Thank you in advance
    Zheng Da
    ThreadPool.java
    package j2me.concurrent;
    import java.util.LinkedList;
    import java.util.Timer;
    import java.util.TimerTask;
    import alvis.general.Util;
    public class ThreadPool {
         private int maxQueueSize;
         private boolean running = true;
         private Thread[] threads;
         private LinkedList tasks = new LinkedList();
         private Timer timer = new Timer(true);
         private AtomicInteger usingThreads = new AtomicInteger(0);
         private synchronized boolean isRunning() {
              return running;
         private synchronized void stopRunning() {
              running = false;
         private synchronized PoolTask getTask() {
              while (tasks.isEmpty() && isRunning()) {
                   try {
                        this.wait();
                   } catch (InterruptedException e) {
                        e.printStackTrace();
              if (tasks.isEmpty())
                   return null;
              // Util.log.info(Thread.currentThread().getName() +
              // " gets a task, left tasks: " + tasks.size());
              return (PoolTask) tasks.removeFirst();
         private synchronized void addTaskNoDelay(PoolTask task) {
              tasks.addLast(task);
              notifyAll();
         private synchronized void addTask(final PoolTask task) {
              long delay = task.delay();
              if (delay == 0) {
                   addTaskNoDelay(task);
              } else {
                   timer.schedule(new TimerTask() {
                        public void run() {
                             addTaskNoDelay(task);
                   }, delay);
         private synchronized int numTasks() {
              return tasks.size();
         private class PoolThread extends Thread {
              public void run() {
                   Util.poolThreads.inc();
                   while (isRunning()) {
                        PoolTask task = getTask();
                        if (task == null) {
                             Util.poolThreads.dec();
                             return;
                        usingThreads.inc();
                        long currentTime = System.currentTimeMillis();
                        task.run();
                        long elapsedTime = System.currentTimeMillis() - currentTime;
                        if (elapsedTime > 100)
                             System.err.println(task.toString() + " takes " + ((double) elapsedTime)/1000 + "s");
                        usingThreads.dec();
                        if (!task.finish()) {
                             addTask(task);
                   Util.poolThreads.dec();
         public ThreadPool(int size, int taskQueueSize) {
              maxQueueSize = taskQueueSize;
              threads = new Thread[size];
              for (int i = 0; i < threads.length; i++) {
                   threads[i] = new PoolThread();
                   threads.start();
         public synchronized boolean executor(PoolTask task) {
              if (!isRunning()) {
                   return false;
              Util.log.info("Thread Pool gets " + task + ", there are "
                        + numTasks() + " waiting tasks");
              if (numTasks() >= maxQueueSize) {
                   return false;
              addTask(task);
              return true;
         public synchronized void destroy() {
              stopRunning();
              timer.cancel();
              // TODO: I am not sure it can wake up all threads and destroy them.
              this.notifyAll();
         public synchronized void printSnapshot() {
              System.err.println("using threads: " + usingThreads + ", remaining tasks: " + tasks.size());
    PoolTask.javapackage j2me.concurrent;
    public interface PoolTask extends Runnable {
         * It shows if the task has already finished.
         * If it isn't, the task will be put in the thread pool for the next execution.
         * @return
         boolean finish();
         * It shows the delay in milliseconds that the task is put in the thread pool.
         * @return
         long delay();

    are receiving/sends tasks packets time consuming operation in your case or not? if it is not you do not need to use thread pools at all. you can create a queue like in your code through the linked list and dispatch this queue periodically with minimum monitor usage. try this.
    import java.util.LinkedList;
    public class PacketDispatcher extends Thread {
        LinkedList list = new LinkedList();
        public PacketDispatcher (String name) {
            super(name);
        public void putTask(Task task) {
            synchronized (list) {
                list
                        .add(task);
                list.notify();
        public void run() {
            while (true/* your condition */) {
                Task task = null;
                synchronized (list) {
                    while (list.isEmpty())
                        try {
                            list.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                    task = (Task)list
                            .poll();
                if (task == null) {
                    try {
                        Thread
                                .sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    continue;
                task
                        .run();
                if (!task.isFinished()) {
                    putTask(task);
                Thread
                        .yield();
        public static void main(String[] args) {
            // just for test
            try {
                Thread.sleep (10000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            PacketDispatcher dispatcher = new PacketDispatcher("Packet Dispatcher");
            Task task = new Task();
            dispatcher.putTask(task);
            dispatcher.start();
            try {
                Thread.sleep (10000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            Task task2 = new Task();
            dispatcher.putTask(task2);
    class Task {
        long result = 0;
        public boolean isFinished () {
            if (getResult() >= 10000000) {
                return true;
            return false;
        public void run() {
            for (int i = 0; i < 1000; i++) {
                result += i;
        public long getResult () {
            return result;       
    }

  • Strange behaviour with Fixed thread pool

    Hi all
    I am trying to learn multithreading. I have written a small snippet of code. After running for around 30 minutes, this code ends up in a deadlock. I am trying to figure out a reason. any help will be really appreciated. Thanks. Following is the code. I am using Ubuntu 10.04 and jdk 1.6.
    package rollerdemo;
    //Simulate a roller coaster, as in exercise 3.5 of Magee and Kramer.
    import java.util.concurrent.CyclicBarrier;
    import java.util.concurrent.BrokenBarrierException;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    //This thread deals with the passengers arriving at random intervals.
    class TurnstileBarrier implements Runnable
         private ControlBarrier controlBarrier;
         private CyclicBarrier cyclicBarrier;
         TurnstileBarrier(ControlBarrier controlBarrier, CyclicBarrier cyclicBarrier) { 
              this.controlBarrier = controlBarrier;
              this.cyclicBarrier = cyclicBarrier;
         public void run(){ 
              try {
                   controlBarrier.welcomePassenger();
                   cyclicBarrier.await();
              } catch (InterruptedException e) {
                   Thread.currentThread().interrupt();               
              } catch (BrokenBarrierException e) {
                   Thread.currentThread().interrupt();               
              } finally {
    class RollerBarrier
         public static int NUMBER_OF_PASSENGERS_PER_CAR = 20;
         public static void main(String[] args) throws InterruptedException
              final ControlBarrier controlBarrier = new ControlBarrier();
              Runnable carBarrier = new Runnable() {
                   public void run(){ 
                        controlBarrier.departCar();
              CyclicBarrier barrier = new CyclicBarrier(NUMBER_OF_PASSENGERS_PER_CAR, carBarrier);
              ExecutorService pool = Executors.newFixedThreadPool(NUMBER_OF_PASSENGERS_PER_CAR);
              while(true)
                   pool.execute(new TurnstileBarrier(controlBarrier,barrier));
    // The Control class represents the state of the controller, and the actions
    // which can be performed.
    class ControlBarrier
         private long queued = 0;
         private long carsSent = 0;
         private long numberOfPassengersTravelledToday = 0;
         ControlBarrier()
              queued = 0;
              carsSent = 0;
              numberOfPassengersTravelledToday = 0;
         synchronized void welcomePassenger() {
              System.out.format("Welcoming Passenger %d%n", ++queued);
              ++numberOfPassengersTravelledToday;
         synchronized void departCar() {
              queued = queued - RollerBarrier.NUMBER_OF_PASSENGERS_PER_CAR;
              System.out.format("The car %d is going now and the number of passengers travelled so far with us is %d%n", ++carsSent, numberOfPassengersTravelledToday);
    }Edited by: 858236 on May 12, 2011 2:35 AM

    Thanks every one for the replies. Really very helpful. After doing the stack -l pid I have got into a confusion. It seems that there is no deadlock but why would all of a sudden the program stop to run. May be I am missing some thing. Just check the stack trace. What I read is that out of 20 threads, 3 threads are waiting on the cyclic barrier await function, while other 17 are waiting to get new tasks from the pool. Am I wrong here? Many thanks.
    2011-05-11 23:42:26
    Full thread dump OpenJDK Client VM (19.0-b09 mixed mode, sharing):
    "Attach Listener" daemon prio=10 tid=0x088fc000 nid=0x34d4 waiting on condition [0x00000000]
       java.lang.Thread.State: RUNNABLE
       Locked ownable synchronizers:
         - None
    "DestroyJavaVM" prio=10 tid=0xb4f21c00 nid=0x2c85 waiting on condition [0x00000000]
       java.lang.Thread.State: RUNNABLE
       Locked ownable synchronizers:
         - None
    "pool-1-thread-20" prio=10 tid=0xb4f20000 nid=0x2ca0 waiting on condition [0xb49ee000]
       java.lang.Thread.State: WAITING (parking)
         at sun.misc.Unsafe.park(Native Method)
         - parking to wait for  <0x7a387350> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
         at java.util.concurrent.locks.LockSupport.park(LockSupport.java:186)
         at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2043)
         at java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:386)
         at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1043)
         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1103)
         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
         at java.lang.Thread.run(Thread.java:636)
       Locked ownable synchronizers:
         - None
    "pool-1-thread-19" prio=10 tid=0xb4f1e800 nid=0x2c9f waiting on condition [0xb4a3f000]
       java.lang.Thread.State: WAITING (parking)
         at sun.misc.Unsafe.park(Native Method)
         - parking to wait for  <0x7a387350> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
         at java.util.concurrent.locks.LockSupport.park(LockSupport.java:186)
         at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2043)
         at java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:386)
         at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1043)
         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1103)
         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
         at java.lang.Thread.run(Thread.java:636)
       Locked ownable synchronizers:
         - None
    "pool-1-thread-18" prio=10 tid=0xb4f1d000 nid=0x2c9e waiting on condition [0xb4a90000]
       java.lang.Thread.State: WAITING (parking)
         at sun.misc.Unsafe.park(Native Method)
         - parking to wait for  <0x7a387350> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
         at java.util.concurrent.locks.LockSupport.park(LockSupport.java:186)
         at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2043)
         at java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:386)
         at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1043)
         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1103)
         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
         at java.lang.Thread.run(Thread.java:636)
       Locked ownable synchronizers:
         - None
    "pool-1-thread-17" prio=10 tid=0xb4f1b800 nid=0x2c9d waiting on condition [0xb4ae1000]
       java.lang.Thread.State: WAITING (parking)
         at sun.misc.Unsafe.park(Native Method)
         - parking to wait for  <0x7a387350> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
         at java.util.concurrent.locks.LockSupport.park(LockSupport.java:186)
         at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2043)
         at java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:386)
         at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1043)
         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1103)
         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
         at java.lang.Thread.run(Thread.java:636)
       Locked ownable synchronizers:
         - None
    "pool-1-thread-16" prio=10 tid=0xb4f19c00 nid=0x2c9c waiting on condition [0xb4b32000]
       java.lang.Thread.State: WAITING (parking)
         at sun.misc.Unsafe.park(Native Method)
         - parking to wait for  <0x7a387350> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
         at java.util.concurrent.locks.LockSupport.park(LockSupport.java:186)
         at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2043)
         at java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:386)
         at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1043)
         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1103)
         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
         at java.lang.Thread.run(Thread.java:636)
       Locked ownable synchronizers:
         - None
    "pool-1-thread-15" prio=10 tid=0xb4f18400 nid=0x2c9b waiting on condition [0xb4b83000]
       java.lang.Thread.State: WAITING (parking)
         at sun.misc.Unsafe.park(Native Method)
         - parking to wait for  <0x7a387350> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
         at java.util.concurrent.locks.LockSupport.park(LockSupport.java:186)
         at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2043)
         at java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:386)
         at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1043)
         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1103)
         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
         at java.lang.Thread.run(Thread.java:636)
       Locked ownable synchronizers:
         - None
    "pool-1-thread-14" prio=10 tid=0xb4f16c00 nid=0x2c9a waiting on condition [0xb4bd4000]
       java.lang.Thread.State: WAITING (parking)
         at sun.misc.Unsafe.park(Native Method)
         - parking to wait for  <0x7a387350> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
         at java.util.concurrent.locks.LockSupport.park(LockSupport.java:186)
         at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2043)
         at java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:386)
         at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1043)
         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1103)
         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
         at java.lang.Thread.run(Thread.java:636)
       Locked ownable synchronizers:
         - None
    "pool-1-thread-13" prio=10 tid=0xb4f15400 nid=0x2c99 waiting on condition [0xb4c25000]
       java.lang.Thread.State: WAITING (parking)
         at sun.misc.Unsafe.park(Native Method)
         - parking to wait for  <0x7a387350> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
         at java.util.concurrent.locks.LockSupport.park(LockSupport.java:186)
         at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2043)
         at java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:386)
         at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1043)
         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1103)
         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
         at java.lang.Thread.run(Thread.java:636)
       Locked ownable synchronizers:
         - None
    "pool-1-thread-12" prio=10 tid=0xb4f13c00 nid=0x2c98 waiting on condition [0xb4c76000]
       java.lang.Thread.State: WAITING (parking)
         at sun.misc.Unsafe.park(Native Method)
         - parking to wait for  <0x7a387350> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
         at java.util.concurrent.locks.LockSupport.park(LockSupport.java:186)
         at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2043)
         at java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:386)
         at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1043)
         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1103)
         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
         at java.lang.Thread.run(Thread.java:636)
       Locked ownable synchronizers:
         - None
    "pool-1-thread-11" prio=10 tid=0xb4f12400 nid=0x2c97 waiting on condition [0xb4cc7000]
       java.lang.Thread.State: WAITING (parking)
         at sun.misc.Unsafe.park(Native Method)
         - parking to wait for  <0x7a387350> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
         at java.util.concurrent.locks.LockSupport.park(LockSupport.java:186)
         at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2043)
         at java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:386)
         at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1043)
         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1103)
         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
         at java.lang.Thread.run(Thread.java:636)
       Locked ownable synchronizers:
         - None
    "pool-1-thread-10" prio=10 tid=0xb4f10c00 nid=0x2c96 waiting on condition [0xb4d18000]
       java.lang.Thread.State: WAITING (parking)
         at sun.misc.Unsafe.park(Native Method)
         - parking to wait for  <0x7a387350> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
         at java.util.concurrent.locks.LockSupport.park(LockSupport.java:186)
         at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2043)
         at java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:386)
         at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1043)
         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1103)
         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
         at java.lang.Thread.run(Thread.java:636)
       Locked ownable synchronizers:
         - None
    "pool-1-thread-9" prio=10 tid=0xb4f0f400 nid=0x2c95 waiting on condition [0xb4d69000]
       java.lang.Thread.State: WAITING (parking)
         at sun.misc.Unsafe.park(Native Method)
         - parking to wait for  <0x7a387350> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
         at java.util.concurrent.locks.LockSupport.park(LockSupport.java:186)
         at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2043)
         at java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:386)
         at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1043)
         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1103)
         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
         at java.lang.Thread.run(Thread.java:636)
       Locked ownable synchronizers:
         - None
    "pool-1-thread-8" prio=10 tid=0xb4f0dc00 nid=0x2c94 waiting on condition [0xb4dba000]
       java.lang.Thread.State: WAITING (parking)
         at sun.misc.Unsafe.park(Native Method)
         - parking to wait for  <0x7a380108> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
         at java.util.concurrent.locks.LockSupport.park(LockSupport.java:186)
         at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2043)
         at java.util.concurrent.CyclicBarrier.dowait(CyclicBarrier.java:227)
         at java.util.concurrent.CyclicBarrier.await(CyclicBarrier.java:355)
         at rollerdemo.TurnstileBarrier.run(RollerBarrier.java:25)
         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
         at java.lang.Thread.run(Thread.java:636)
       Locked ownable synchronizers:
         - <0x7a3808d8> (a java.util.concurrent.ThreadPoolExecutor$Worker)
    "pool-1-thread-7" prio=10 tid=0xb4f0c800 nid=0x2c93 waiting on condition [0xb4e0b000]
       java.lang.Thread.State: WAITING (parking)
         at sun.misc.Unsafe.park(Native Method)
         - parking to wait for  <0x7a387350> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
         at java.util.concurrent.locks.LockSupport.park(LockSupport.java:186)
         at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2043)
         at java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:386)
         at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1043)
         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1103)
         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
         at java.lang.Thread.run(Thread.java:636)
       Locked ownable synchronizers:
         - None
    "pool-1-thread-6" prio=10 tid=0xb4f0b400 nid=0x2c92 waiting on condition [0xb4e5c000]
       java.lang.Thread.State: WAITING (parking)
         at sun.misc.Unsafe.park(Native Method)
         - parking to wait for  <0x7a387350> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
         at java.util.concurrent.locks.LockSupport.park(LockSupport.java:186)
         at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2043)
         at java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:386)
         at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1043)
         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1103)
         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
         at java.lang.Thread.run(Thread.java:636)
       Locked ownable synchronizers:
         - None
    "pool-1-thread-5" prio=10 tid=0xb4f09800 nid=0x2c91 waiting on condition [0xb4ead000]
       java.lang.Thread.State: WAITING (parking)
         at sun.misc.Unsafe.park(Native Method)
         - parking to wait for  <0x7a387350> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
         at java.util.concurrent.locks.LockSupport.park(LockSupport.java:186)
         at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2043)
         at java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:386)
         at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1043)
         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1103)
         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
         at java.lang.Thread.run(Thread.java:636)
       Locked ownable synchronizers:
         - None
    "pool-1-thread-4" prio=10 tid=0xb4f08400 nid=0x2c90 waiting on condition [0xb4efe000]
       java.lang.Thread.State: WAITING (parking)
         at sun.misc.Unsafe.park(Native Method)
         - parking to wait for  <0x7a380108> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
         at java.util.concurrent.locks.LockSupport.park(LockSupport.java:186)
         at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2043)
         at java.util.concurrent.CyclicBarrier.dowait(CyclicBarrier.java:227)
         at java.util.concurrent.CyclicBarrier.await(CyclicBarrier.java:355)
         at rollerdemo.TurnstileBarrier.run(RollerBarrier.java:25)
         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
         at java.lang.Thread.run(Thread.java:636)
       Locked ownable synchronizers:
         - <0x7a382cd0> (a java.util.concurrent.ThreadPoolExecutor$Worker)
    "pool-1-thread-3" prio=10 tid=0xb4f07000 nid=0x2c8f waiting on condition [0xb5053000]
       java.lang.Thread.State: WAITING (parking)
         at sun.misc.Unsafe.park(Native Method)
         - parking to wait for  <0x7a387350> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
         at java.util.concurrent.locks.LockSupport.park(LockSupport.java:186)
         at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2043)
         at java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:386)
         at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1043)
         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1103)
         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
         at java.lang.Thread.run(Thread.java:636)
       Locked ownable synchronizers:
         - None
    "pool-1-thread-2" prio=10 tid=0xb4f05800 nid=0x2c8e waiting on condition [0xb50a4000]
       java.lang.Thread.State: WAITING (parking)
         at sun.misc.Unsafe.park(Native Method)
         - parking to wait for  <0x7a380108> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
         at java.util.concurrent.locks.LockSupport.park(LockSupport.java:186)
         at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2043)
         at java.util.concurrent.CyclicBarrier.dowait(CyclicBarrier.java:227)
         at java.util.concurrent.CyclicBarrier.await(CyclicBarrier.java:355)
         at rollerdemo.TurnstileBarrier.run(RollerBarrier.java:25)
         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
         at java.lang.Thread.run(Thread.java:636)
       Locked ownable synchronizers:
         - <0x7a382e00> (a java.util.concurrent.ThreadPoolExecutor$Worker)
    "pool-1-thread-1" prio=10 tid=0xb4f04800 nid=0x2c8d waiting on condition [0xb50f5000]
       java.lang.Thread.State: WAITING (parking)
         at sun.misc.Unsafe.park(Native Method)
         - parking to wait for  <0x7a387350> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
         at java.util.concurrent.locks.LockSupport.park(LockSupport.java:186)
         at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2043)
         at java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:386)
         at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1043)
         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1103)
         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
         at java.lang.Thread.run(Thread.java:636)
       Locked ownable synchronizers:
         - None
    "Low Memory Detector" daemon prio=10 tid=0x08938000 nid=0x2c8b runnable [0x00000000]
       java.lang.Thread.State: RUNNABLE
       Locked ownable synchronizers:
         - None
    "CompilerThread0" daemon prio=10 tid=0x08936000 nid=0x2c8a waiting on condition [0x00000000]
       java.lang.Thread.State: RUNNABLE
       Locked ownable synchronizers:
         - None
    "Signal Dispatcher" daemon prio=10 tid=0x08934800 nid=0x2c89 runnable [0x00000000]
       java.lang.Thread.State: RUNNABLE
       Locked ownable synchronizers:
         - None
    "Finalizer" daemon prio=10 tid=0x0892c800 nid=0x2c88 in Object.wait() [0xb5339000]
       java.lang.Thread.State: WAITING (on object monitor)
         at java.lang.Object.wait(Native Method)
         - waiting on <0x7a383068> (a java.lang.ref.ReferenceQueue$Lock)
         at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:133)
         - locked <0x7a383068> (a java.lang.ref.ReferenceQueue$Lock)
         at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:149)
         at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:177)
       Locked ownable synchronizers:
         - None
    "Reference Handler" daemon prio=10 tid=0x0892b000 nid=0x2c87 in Object.wait() [0xb538a000]
       java.lang.Thread.State: WAITING (on object monitor)
         at java.lang.Object.wait(Native Method)
         - waiting on <0x7a3830f0> (a java.lang.ref.Reference$Lock)
         at java.lang.Object.wait(Object.java:502)
         at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:133)
         - locked <0x7a3830f0> (a java.lang.ref.Reference$Lock)
       Locked ownable synchronizers:
         - None
    "VM Thread" prio=10 tid=0x08929400 nid=0x2c86 runnable
    "VM Periodic Task Thread" prio=10 tid=0x08943c00 nid=0x2c8c waiting on condition
    JNI global references: 983

  • Fixed Size Thread Pool which infinitely serve task submitted to it

    Hi,
    I want to create a fixed size thread pool say of size 100 and i will submit around 200 task to it.
    Now i want it to serve them infinitely i.e once all tasks are completed re-do them again and again.
    public void start(Vector<String> addresses)
          //Create a Runnable object of each address in "addresses"
           Vector<FindAgentRunnable> runnables = new Vector<FindAgentRunnable>(1,1);
            for (String address : addresses)
                runnables.addElement(new FindAgentRunnable(address));
           //Create a thread pool of size 100
            ExecutorService pool = Executors.newFixedThreadPool(100);
            //Here i added all the runnables to the thread pool
             for(FindAgentRunnable runnable : runnables)
                    pool.submit(runnable);
                pool.shutdown();
    }Now i wants that this thread pool execute the task infinitely i.e once all the tasks are done then restart all the tasks again.
    I have also tried to add then again and again but it throws a java.util.concurrent.RejectedExecutionException
    public void start(Vector<String> addresses)
          //Create a Runnable object of each address in "addresses"
           Vector<FindAgentRunnable> runnables = new Vector<FindAgentRunnable>(1,1);
            for (String address : addresses)
                runnables.addElement(new FindAgentRunnable(address));
           //Create a thread pool of size 100
            ExecutorService pool = Executors.newFixedThreadPool(100);
            for(;;)
                for(FindAgentRunnable runnable : runnables)
                    pool.submit(runnable);
                pool.shutdown();
                try
                    pool.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
                catch (InterruptedException ex)
                    Logger.getLogger(AgentFinder.class.getName()).log(Level.SEVERE, null, ex);
    }Can anybody help me to solve this problem?
    Thnx in advance.

    Ravi_Gupta wrote:
    *@ kajbj*
    so what should i do?
    can you suggest me a solution?Consider this thread "closed". Continue to post in your other thread. I, and all others don't want to give answers that already have been given.

  • Fixed size thread pool excepting more tasks then it should

    Hello,
    I have the following code in a simple program (code below)
              BlockingQueue<Runnable> q = new ArrayBlockingQueue<Runnable>(10, false);
              ThreadPoolExecutor newPool = new ThreadPoolExecutor(1, 10, 20, TimeUnit.SECONDS, q);
    for (int x = 0; x < 30; x++) {
    newPool.execute(new threaded());
    My understanding is that this should create a thread pool that will accept 10 tasks, once there have been 10 tasks submitted I should get RejectedExecutionException, however; I am seeing that when I execute the code the pool accepts 20 execute calls before throwing RejectedExecutionException. I am on Windows 7 using Java 1.6.0_21
    Any thoughts on what I am doing incorrectly?
    Thanks
    import java.util.concurrent.*;
    public class ThreadPoolTest {
         public static class threaded implements Runnable {
              @Override
              public void run() {
                   System.out.println("In thread: " + Thread.currentThread().getId());
                   try {
                        Thread.sleep(5000);
                   } catch (InterruptedException e) {
                        System.out.println("Thread: " + Thread.currentThread().getId()
                                  + " interuptted");
                   System.out.println("Exiting thread: " + Thread.currentThread().getId());
         private static int MAX = 10;
         private Executor pool;
         public ThreadPoolTest() {
              super();
              BlockingQueue<Runnable> q = new ArrayBlockingQueue<Runnable>(MAX/2, false);
              ThreadPoolExecutor newPool = new ThreadPoolExecutor(1, MAX, 20, TimeUnit.SECONDS, q);
              pool = newPool;
         * @param args
         public static void main(String[] args) {
              ThreadPoolTest object = new ThreadPoolTest();
              object.doThreads();
         private void doThreads() {
              int submitted = 0, rejected = 0;
              for (int x = 0; x < MAX * 3; x++) {
                   try {
                        System.out.println(Integer.toString(x) + " submitting");
                        pool.execute(new threaded());
                        submitted++;
                   catch (RejectedExecutionException re) {
                        System.err.println("Submission " + x + " was rejected");
                        rejected++;
              System.out.println("\n\nSubmitted: " + MAX*2);
              System.out.println("Accepted: " + submitted);
              System.out.println("Rejected: " + rejected);
    }

    I don't know what is wrong because I tried this
    public static void main(String args[])  {
        BlockingQueue<Runnable> q = new ArrayBlockingQueue<Runnable>(10, false);
        ThreadPoolExecutor newPool = new ThreadPoolExecutor(1, 10, 20, TimeUnit.SECONDS, q);
        for (int x = 0; x < 100; x++) {
            System.err.println(x + ": " + q.size());
            newPool.submit(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    Thread.sleep(1000);
                    return null;
    }and it printed
    0: 0
    1: 0
    2: 1
    3: 2
    4: 3
    5: 4
    6: 5
    7: 6
    8: 7
    9: 8
    10: 9
    11: 10
    12: 10
    13: 10
    14: 10
    15: 10
    16: 10
    17: 10
    18: 10
    19: 10
    20: 10
    Exception in thread "main" java.util.concurrent.RejectedExecutionException
         at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:1768)
         at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:767)
         at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:658)
         at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:92)
         at Main.main(Main.java:36)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:597)
         at com.intellij.rt.execution.application.AppMain.main(AppMain.java:115)Ihave Java 6 update 24 on Linux, but I don't believe this should make a difference. Can you try my code?

  • Thread pool with AT MOST one thread at a time

    Hi,
    I want to create a pool that creates at most one thread when it is needed. I want the pool to terminate the thread when it is idle for some time. Executors.newSingleThreadExecutor() creates a thread pool with one thread, but this thread doesn't die if idle...
    The code below also doesn't work - no thread is ever created:
    new ThreadPoolExecutor(0, 1, 30, TimeUnit.SECONDS,
                              new LinkedBlockingQueue<Runnable>());Thanks in advance

    Use Future.get().
    package net.jcip.examples;
    import java.util.concurrent.*;
    import static java.util.concurrent.TimeUnit.NANOSECONDS;
    * RenderWithTimeBudget
    * Fetching an advertisement with a time budget
    * @author Brian Goetz and Tim Peierls
    public class RenderWithTimeBudget {
        private static final Ad DEFAULT_AD = new Ad();
        private static final long TIME_BUDGET = 1000;
        private static final ExecutorService exec = Executors.newCachedThreadPool();
        Page renderPageWithAd() throws InterruptedException {
            long endNanos = System.nanoTime() + TIME_BUDGET;
            Future<Ad> f = exec.submit(new FetchAdTask());
            // Render the page while waiting for the ad
            Page page = renderPageBody();
            Ad ad;
            try {
                // Only wait for the remaining time budget
                long timeLeft = endNanos - System.nanoTime();
                ad = f.get(timeLeft, NANOSECONDS);
            } catch (ExecutionException e) {
                ad = DEFAULT_AD;
            } catch (TimeoutException e) {
                ad = DEFAULT_AD;
                f.cancel(true);
            page.setAd(ad);
            return page;
        Page renderPageBody() { return new Page(); }
        static class Ad {
        static class Page {
            public void setAd(Ad ad) { }
        static class FetchAdTask implements Callable<Ad> {
            public Ad call() {
                return new Ad();
    }

Maybe you are looking for

  • How do I reset instruments like ResMan in my Operato Interface

    I have a requirement to be able to reset all of my instruments from within my LabWindows Operator Interface each time a user logs in. I know where to put the code, I just need to know what to put there. I've had NiSpy active while ResMan is running,

  • App that handles pdf and .doc and .eml like Coverflow on steroids?

    Is there an app that would let me basically scroll through a folder with the pdfs, Pages, and/or saved email visible at actual size (8 1/2 x 11) or some other realistically sized almost full screen method? As I new user I absolutely /love/ Coverflow

  • Panic! Possible to change Fontcolor in List in AWT?

    I really need to know if it is possible to change the font color in AWT for different list entries in th awt.List object. I managed to change the fonts with no problem, but the font color... I�m using my list as an own object which extends the panel.

  • Digital signature in SharePoint hosted app

    I am creating a sharepoint hosted app where user must use digital signature(loginname, password) before submitting request. I am unable to find any machenism to validate user credentials using jquery/javascript.

  • Submit button in Interactive form WDA

    Hi All, I have created one WD ABAP interactive form using one BAPI. I have placed one Submit button on the form which is of type (webdynpro native). And i have defined on action in WD. But when I click on submit button the action is not trigerring. I