5.0's ThreadPoolExecutor

It appears that this implementation replaces the thread that ran a task with a brand-new thread. If i understand this correctly, why not keep the thread around in waiting state until another task comes up, and then wake it up when the new task comes in? I read something that it might be more robust to replace a thread after an exception, but in this case, even that is not being considered, from what i see. The replacement is done regardless of whether there have been exceptions.
The only thing i can think of why that is done is to have a fresh start every time, for robustness. In that case, how risky is it to have a thread pool that keeps the threads in waiting state, and then wakes them up as tasks arrive, and then puts into waiting state again, and so on?
Thanks.

Looking at the source code. I may be mistaken, but from the code below, i conclude it replaces threads with new ones, instead of keeping threads in wait state.
My understanding is as follows, starting at first execute call:
TPE.addIfUnderCorePoolSize->TPE.addThread->Thread.start->Thread.run->
while(<hasTask>)
Runnable.run->TPE.workerDone
If pool size becomes 0 in TPE.workerDone, then TPE replaces the running thread with a new one, otherwise the running thread completes its execution, and we have one thread less. I.e., when there are no tasks to run, the TPE will have no threads in the pool. This is my understanding, but if it's not correct (i didn't have a lot of time to look thru the code), please correct.
A thread pool that i made for our application (we can't use 1.5, and external libraries aren't very welcome; not my call), keeps the threads in waiting state when there are no tasks to run. That's why i wonder...
Thanks.
    private Thread addThread(Runnable firstTask) {
        Worker w = new Worker(firstTask);
        Thread t = threadFactory.newThread(w);
        if (t != null) {
            w.thread = t;
            workers.add(w);
            int nt = ++poolSize;
            if (nt > largestPoolSize)
                largestPoolSize = nt;
        return t;
    private boolean addIfUnderCorePoolSize(Runnable firstTask) {
        Thread t = null;
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            if (poolSize < corePoolSize)
                t = addThread(firstTask);
        } finally {
            mainLock.unlock();
        if (t == null)
            return false;
        t.start();
        return true;
        public void run() {
            try {
                Runnable task = firstTask;
                firstTask = null;
                while (task != null || (task = getTask()) != null) {
                    runTask(task);
                    task = null; // unnecessary but can help GC
            } catch(InterruptedException ie) {
                // fall through
            } finally {
                workerDone(this);
    void workerDone(Worker w) {
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            completedTaskCount += w.completedTasks;
            workers.remove(w);
            if (--poolSize > 0)
                return;
            // Else, this is the last thread. Deal with potential shutdown.
            int state = runState;
            assert state != TERMINATED;
            if (state != STOP) {
                // If there are queued tasks but no threads, create
                // replacement thread. We must create it initially
                // idle to avoid orphaned tasks in case addThread
                // fails.  This also handles case of delayed tasks
                // that will sometime later become runnable.
                if (!workQueue.isEmpty()) {
                    Thread t = addThread(null);
                    if (t != null)
                        t.start();
                    return;
                // Otherwise, we can exit without replacement
                if (state == RUNNING)
                    return;
            // Either state is STOP, or state is SHUTDOWN and there is
            // no work to do. So we can terminate.
            termination.signalAll();
            runState = TERMINATED;
            // fall through to call terminate() outside of lock.
        } finally {
            mainLock.unlock();
        assert runState == TERMINATED;
        terminated();
    }

Similar Messages

  • ThreadPoolExecutor with LinkedBlockingQueue doesn't work?

    I've tried creating a worker pool by using a LinkedBlockingQueue like so -
    new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L,
    TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()). But none of my submitted jobs are getting executed. I don't even see any Threads being created to handle the jobs.
    However if I create a
    new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L,
    TimeUnit.SECONDS, new SynchronousQueue<Runnable>()) everything works fine.
    This was on RHEL, 64 bit running a 64-Bit Server VM (build 1.5.0_15-b04).
    Has anyone else noticed this before?
    Edited by: Ashwin.Jayaprakash on Aug 6, 2008 11:39 AM
    Edited by: Ashwin.Jayaprakash on Aug 6, 2008 11:40 AM
    Edited by: Ashwin.Jayaprakash on Aug 6, 2008 11:41 AM

    This is a "feature" of Java 5. If the job can be added to the queue, no additional threads are created. Since you start with no threads this is not a useful configuration in the first case. Java 6 is a little smarter and create at least one thread even if the task can be added to the queue. (but it won't create more)

  • How can I close core thread in ThreadPoolExecutor?

    If I use unbounded LinkedBlockingQueue in ThreadPoolExecutor and set the core pool size to 5. When more than 5 tasks are submitted, there will be 5 threads created to handle the request. After finish, these threads will not be closed. How can I make the threads in core pool be closed when finishing their job? I couldn't use maximum pool for that I do need an unbounded queue.

    If you really want that functionality, set the core pool size to 0, the maximum pool size to 5 or greater, and the keepAliveTime to 0L. This will remove excess threads as soon as their tasks have completed.
    It's very wasteful though if you plan on executing the tasks repeatedly to create new threads everytime you submit a task. One of the benefits of using a thread executor is not having to construct and start a Thread object everytime you run a task.
    Brushfire,

  • Problem when using ThreadPoolExecutor under Linux

    I am writing a multithreading web page fetcher under windows with jdk1.5.0-09. I have a task dispatcher like this:
    public void run() {
         while (true) {
              try {
               if(_fetcherPool.getActiveCount()<_config.numThreads){
                   _fetcherPool.execute(new RobotstxtFetcher(_crawler, getURLQueue().take()));
                } else {
                   Thread.sleep(someDelay);
              } catch (InterruptedException e) {
                   log.error("Dispatcher.run", e);
    }Everything works fine as expected, 500 threads are generated, and new tasks will be submitted to the pool. I got performance of finishing 20 tasks per second.
    But when I moved this program to Redhat Enterprise Linux with jdk1.5.0_09, the behavior changed completely. 500 threads are still generated. But they are not processing anything for about 60 seconds, but then suddenly finished about 300 tasks in 1-2 seconds. Then the program will wait for another 60 seconds and then finish 300 tasks in 1-2 seconds again.
    So I tried to test it with multithread without using threadpoolexecutor. I generated 500 threads, and each thread get tasks from the queue directly without thread pooling. It works fine just as under windows.
    Can anyone tell me why?
    BTW, I suspect the creation of the thread pool may be an issue. Here's my code:
    ThreadPoolExecutor _fetcherPool = new ThreadPoolExecutor(
         500, 500+20, 1, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>() );Please help. Thanks.
    Message was edited by:
    okss

    I can't see the picture. Maybe host somewhere else and post a link?

  • How to use ThreadPoolExecutor / ArrayBlockingQueue with event objects

    I am having some trouble figuring out how to use the new java.util.concurrent library for a simple thread pool that has custom threads pulling off event objects from a queue.
    I started with this kind of code below, which I know is not right but am having trouble seeing the correct approach. Any help is appreciated. Thank You!
    -Paul
    public class testThreadPool {
    public static void main( String [] args ) {
    //work queue actaully only takes runnables,
    //but I need to add my event objects to this queue ??
    ArrayBlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<Runnable>(20);
    ThreadPoolExecutor pool = new ThreadPoolExecutor(10,//pool size
    20,//max pool size
    1,
    TimeUnit.SECONDS,
    workQueue);//the work queue
    //this will ensure that the pool executor creates worker
    //threads of type MyThreadWorker
    pool.setThreadFactory(new MyThreadFactory());
    pool.prestartAllCoreThreads();
    //throw some events on the queue and let the pool workers
    //start to execute with the given event object
    workQueue.add(MyEvent);
    workQueue.add(AnotherEvent);
    class MyThreadFactory implements ThreadFactory {
    public Thread newThread(Runnable runnable) {
    return new (Thread)MyThreadWorker();
    class MyThreadWorker implements Runnable {
    private boolean m_run = true;
    public void run(){
    Object obj;
    while (m_run) {
    obj = null;
    //get the event object from the blocking queue
    try {
    obj = workQueue.take();
    } catch (InterruptedException e) {
    if ( obj == null ) continue;
    if ( obj == null ) continue;
    if (obj instanceof MyEvent) {
    //do this
    } else if (obj instanceof AnotherEvent) {
    //do this
    public void stopRunning(){
    m_run = false;
    this.interrupt();
    }

    What database and connection type are you using? Are you connecting the report directly to the database, or trying to assign the datasource to object data?
    It sounds like you might be trying to use a linked list, collection or other C# construct to pass your data in. This currently isn't supported by the Crystal Reports SDK. You can use a DataSet or a DataTable, and possibly also an IDataReader depending on which version of Crystal Reports you're referencing in your project. Of course you can also connect directly to the database, even if the database isn't on the same machine as the application.
    The way to show master records with detail information is through the use of subreports and linked subreport parameters. Linked subreports take their parameter value from a record in the main report, so that only the data appropriate to that master record is displayed. The guys over in the [report design|SAP Crystal Reports; forum can help you out with this if you have questions on the specifics.

  • ThreadPoolExecutor with dynamic sizing

    ExecutorService executor = new
    ThreadPoolExecutor(1, 5, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());with the above piece of code in our application, the number of processor/active threads doesn't go above 1.
    when i analyzed the behavior with a profiling tool, i see that there is no more free time for the single thread to process the runnable tasks. In this case why doesn't the executor let one (or more) threads to work on the runnables that are piling up the queue and then (later when the queue is nearing empty) shutdown the extra threads (after waiting for the given 10 seconds).
    or i got the concept wrong?

    Let's answer a few of your questions:
    kramasundar wrote:
    1. How (using which metric/statistics) does the executor decide that it has to create a new thread (say the second or third or fourth or fifth thread)?
    currently i am looking into the JDK implementation to figure this out.The executors don't use any statistics or metrics. It is quite simple, and defined in the API: ThreadPoolExecutor
    1) If the number of threads is less than the corePoolSize, create a new Thread to run a new task
    2) If the number of threads is equal (or greater than) the corePoolSize, put the task into the queue
    3) If the queue is filled, and the number of threads is less than the maxPoolSize, create a new thread to run tasks in.
    4) If the queue is filled, and the number of threads is greater than or equal to maxPoolSize, reject the task.
    kramasundar wrote:
    I didn't know the magic behind the SynchronousQueue. ...
    In the case of LinkedBlockingQueue we dont have to care about the size issue right?There is no magic. With SynchronousQueue, the queue has no capacity. which means the queue is 'always filled' which means new threads will be created up through the maxPoolSize. Then, when new tasks get added, if there isn't an idle thread they get rejected.
    For the LinkedBlockingQueue, the queue is unbounded, it never gets filled. Which means new threads will ONLY be created up through the corePoolSize, after which all your tasks get queued up. This is important in your case because you keep using a corePoolSize of 1 with an unbounded queue - so no more than 1 thread will be used.
    kramasundar wrote:
    2. Here the executor created 1 thread only. Also i could see that one thread was not enough to handle the load. The throughput was ~ 4000 TPS (i am telling you this since the next run 3 runs fine with higher TPS).
    _executor = new ThreadPoolExecutor(1, 20, 60, TimeUnit.SECONDS,
    new ArrayBlockingQueue<Runnable>(100), new SimpleThreadFactory());3. Here the executor created 15 threads (but not more). Nevertheless the TPS is higher ~12000 TPS. This run confirms that in run 2 Executor could have spawned some more threads to increase the TPS.
    _executor = new ThreadPoolExecutor(15, 20, 60, TimeUnit.SECONDS,
    new ArrayBlockingQueue<Runnable>(100), new SimpleThreadFactory());Does the above runs conclude that in run 2 a queue of size 100 is never full. If it had been full atleast once then the executor would have spawned another thread?First: "This run confirms that in run 2 Executor could have spawned some more threads to increase the TPS."
    No, this confirms that you could configure the executor to run more threads. The executor can't do more than what it is configured to do. It can't spawn new threads to increase your metric of speed, it can only create threads following its own, well defined set of rules.
    Now, " Does the above runs conclude that in run 2 a queue of size 100 is never full. If it had been full atleast once then the executor would have spawned another thread?"
    That is the conclusion I would make, yes. As Kajbj said, otherwise you would see rejected executions.

  • Changing ThreadPoolExecutor to prefer thread use to bounded queue

    I would like to extend ThreadPoolExecutor to create new threads up to maximumPoolSize and then put tasks onto a bounded queue. (Kind of a cross between Fixed and Cached thread pools).
    It seems that the only place to do this would be to rewrite the execute method of ThreadPoolExecutor and swap the following commands
    if (workQueue.offer(command))  // Swap this
      return;
    Runnable r = addIfUnderMaximumPoolSize(command);  // with this
    if (r == command)
      return;
    if (r == null)
      reject(command).
    ...However with most methods and vars private in ThreadPoolExecutor, overriding this method is nearly impossible.
    Is there a better way of doing this?
    Thanks,
    Chris

    nope - there is no chance. sadly not! otherwise i would have integrated it into my templates
    btw - you could change all the links into a rollover, but that would mean that ALL links are a rollover.
    another way is to use iwebmore to edit the template files: http://iwebmore.ctrl-j.eu/iWebMore.html
    max karreth

  • Know if work in a ThreadPoolExecutor is finished

    Hi,
    I have a thread pool which is constructed in the following way:
    ThreadPoolExecutor myThreadPool = new ThreadPoolExecutor(POOL_SIZE, POOL_SIZE, 5, TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>(WORK_QUEUE_SIZE));I'm using the execute method in order to run tasks using the thread pool. I want to know how can I know if all work is done. I cannot wait for each task to finish, instead I have to get this information from the thread pool.
    I tried the following code:
    (myThreadPool.getQueue().size() > 0) && (myThreadPool.getActiveCount() > 0)but I'm not sure if it is good enough.
    Thanks.

    r035198x wrote:
    sabre150 wrote:
            pool.shutdown(); // Stops any further tasks being added
    pool.awaitTermination(100, TimeUnit.MINUTES); // Waits 100 minutes - change the value and units to suit.
    Isn't that cheating?No! It's what the Javadoc says to do.
    >
    If the OP's requirements allow shutting it down first then sure.True - but if it's not then he can never know if all the tasks have finished since without the shutdown() more can be added at any time.
    The problem is that the OP has stated those requirements well enough, IMO.To me there is an implied requirement that he is not going to add more tasks. In these forums if we waited for people to detail their requirements then we would never be able answer anything. It is quite common that a poster does not understand the implications of his question so one has to try to lead him in a direction that will make him understand. If this shutdown() is not a requirement then the OP will quite quickly find out during testing and then at that point I expect the OP to explain why he can't use shutdown().
    I gave the hint of the methods to use and mentioned the Javadoc so I expect the OP to go an read the Javaoc. If he does not then that is his problem.

  • ThreadPoolExecutor and using priority to determine what threads will run

    Hello,
    I am fairly new to Java, so I apologize if there is an obvious answer.
    The ThreadPoolExecutor is a great class for thread management. What I would like to do is have a priority scheme that would determine what thread should be run next. For example, let's say I have 100 threads and a limit of 20 threads. Each thread that is executed should have a mechanism to indicate a priority. When a thread becomes available in the pool, the priority value should be checked to determine which thread to run. This would allow me to get important tasks completed quickly. Right now it appears that there is a FIFO order to threads. I tried wrapping the runnable object in a Thread, but that didn't seem to have an effect.
    I am using a Fixed thread Pool:
          loThreadPoolExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(MAXTHREADS); (MAXTHREADS=20)I have tried creating a PriorityBlockingQueue with a comparator that compares the thread priority, but nothing seems to work.
      public Constructor() {
    loThreadPoolExecutor = new ThreadPoolExecutor(MAXTHREADS,MAXTHREADS*2,0,TimeUnit.SECONDS,new PriorityBlockingQueue(11,new PrvComparator()));
        private class PrvComparator implements Comparator  {
              public int compare(Object o1, Object o2) {
                   // TODO Auto-generated method stub
                   Thread t1 = (Thread) o1;
                   Thread t2 = (Thread) o2;
                   System.out.println("P1="+t1.getPriority()+ " P2="+t2.getPriority());
                   if (t1.getPriority()<t2.getPriority()) return -1;
                   if (t1.getPriority()>t2.getPriority()) return 1;
                   else return 0;
                   //PriorityBlockingQueue
              }I would appreciate any help.

    What are you trying to prioritize? The order on which tasks come off the work queue, or the order in which they get completed?
    Doing the first is simple but restricted. Your tasks are Comparable and define their own priority and you use a PriorityBlockingQueue. But you are restricted to using the execute() method with Runnable's that are Comparable. submit() will wrap the task in a FutureTask that isn't Comparable and so will cause a ClassCastException.
    Doing the second is difficult. Even if your threads have different priorities then don't queue for tasks in priority order, so the thread priority when taking a task is irrelevant. You could change the thread priority based on the priority of the task once it starts executing. But Thread priorities are only a hint to the scheduler that you think Thread A is more important than Thread B. On some platforms priorities will have little observable effects - whereas on other it can be drastic if you use priorities that are too high or too low. The mapping from Java priority to OS thread priority is platform specific. See for example http://java.sun.com/javase/6/docs/technotes/guides/vm/thread-priorities.html

  • Custom ThreadPoolExecutor

    Hello,
    Suppose you need a thread pool with the following behavior:
    maxThreads = Max number of threads can be in the pool.
    If a thread have been idle for more than X seconds, then the thread must die.
    When a task is submitted:
    if (there is an idle thread in the pool) {
        use the idle thread to execute the task.
    } else {
        if (current number of threads < MaxThreads) {
            create a new thread and use it to execute the task.
        } else {
            put the task in a queue.
            the task will be executed when a thread becomes available.
    }How can configure a ThreadPoolExecutor to achieve this?
    If you use this:
    new ThreadPoolExecutor(maxThreads, maxThreads, X, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>())All the threads are in the core, so when you submit a task, a new thread will be created even if there are idle threads in the pool.
    Besides, the core threads don't die by timeout.
    If you use this:
    new ThreadPoolExecutor(0, maxThreads, X, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>())The executor prefer to queue the tasks even if there are idle threads or more threads can be created.
    Thanx

    JoseLuis wrote:
    Hello,
    Suppose you need a thread pool with the following behavior:
    maxThreads = Max number of threads can be in the pool.
    If a thread have been idle for more than X seconds, then the thread must die.
    When a task is submitted:
    if (there is an idle thread in the pool) {
    use the idle thread to execute the task.
    } else {
    if (current number of threads < MaxThreads) {
    create a new thread and use it to execute the task.
    } else {
    put the task in a queue.
    the task will be executed when a thread becomes available.
    }How can configure a ThreadPoolExecutor to achieve this?
    If you use this:
    new ThreadPoolExecutor(maxThreads, maxThreads, X, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>())All the threads are in the core, so when you submit a task, a new thread will be created even if there are idle threads in the pool.
    Besides, the core threads don't die by timeout.Not by default but if you use [ThreadPoolExecutor#allowCoreThreadTimeOut(boolean)|http://java.sun.com/javase/6/docs/api/java/util/concurrent/ThreadPoolExecutor.html#allowCoreThreadTimeOut(boolean)] they do.
    >
    If you use this:
    new ThreadPoolExecutor(0, maxThreads, X, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>())The executor prefer to queue the tasks even if there are idle threads or more threads can be created.If you want to follow this route you should use a bounded BlockingQueue, like an ArrayBlockingQueue, which will force new thread creation when the Queue is full.
    ThreadPoolExecutor executor = new ThreadPoolExecutor(maxThreads/2, maxThreads, X TimeUnit.Seconds, new ArrayBlockingQueue<Runnable>(maxThreads/2));
    executor.allowCoreThreadTimeOut(true);Gets you near where you want, I think.
    >
    Thanx

  • How to rename Threads in ThreadPoolExecutor

    This is the code
    public static void main(String[] args) {
              ThreadPoolExecutor pool = new ThreadPoolExecutor(5, 5, 2, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10));
              for (int i = 0; i< 100; i++) {
                   try {
                        pool.execute(new Task());
                   } catch (RejectedExecutionException e) {
                        e.printStackTrace();
    private class Task implements Runnable {
              public void run() {
                   System.out.println("my current thread is " + Thread.currentThread().getName());
         }This is the output
    my current thread is pool-1-thread-2
    my current thread is pool-1-thread-1
    my current thread is pool-1-thread-3
    my current thread is pool-1-thread-4
    my current thread is pool-1-thread-5I want the thread's name to be "WORKER-" + threadCounter. How do I do that?
    Thanks!

    May I - less than a month after, sorry it took me so long to register to the new forums- suggest the following, which uses delegation to avoid copying the behaviour inside the DefaultThreadFactory:
    * Provides name customization for threads produced by a
    * {@link Executors#defaultThreadFactory()}.
    * @author mbindels
    class NamingThreadFactory implements ThreadFactory {
         ThreadFactory delegate;
         String pattern;
         String replacement;
          * No more <code>pool-N-thread-M</code>, but <i>Your Name Here</i><code>-thread-M</code>
          * @param poolName your pool name
         public NamingThreadFactory(String poolName) {
              this("^pool-\\d+-", poolName+"-", Executors.defaultThreadFactory());
         protected NamingThreadFactory(String pattern, String replacement, ThreadFactory factory) {
              this.pattern = pattern;
              this.replacement = replacement;
              this.delegate = factory;
         @Override
         final public Thread newThread(Runnable r) {
              Thread thread = delegate.newThread(r);
              thread.setName(rename(thread.getName()));
              return thread;
         protected String rename(String oldName) {
              return oldName.replaceAll(pattern, replacement);
    }

  • ThreadPoolExecutor in a JEE Application Server

    Our application runs inside a jee application server.
    We have tasks (implemented as a pojo) that need to be queued and executed by asynchronous threads.
    We came across the new java.util.concurrent.ThreadPoolExecutor,
    which seems to be exactly what we need.
    However, as far as we know threads should be created ONLY by the jee application server.
    Does this mean we can't use the ThreadPoolExecutor class in a jee application server?
    If so what is the best practise for queueing tasks that need to be executed by a configurable pool of worker threads?
    p.s
    We are aware that JMS is also an option, but it entails a bit of an overhead in our case because the tasks are INTERNAL to the local application server ( so there is no need for messaging between 2 application servers).
    thanks
    John

    JMS is certainly a solution to this problem.
    JMX service MBeans are also a solution. they are a technology which was sort of (poorly) adopted into j2ee without a lot of specification about how to control them (just that they are there and can be used). on jboss, there are some proprietary extensions which make it very easy to setup a JMX MBean. i'm sure other app servers have similar facilities. anyway, MBeans do not have the concurrency restrictions of EJB's as they are singleton services, so that is where i would put such a worker thread pool.

  • Collecting Exceptions from Threads in ThreadPoolExecutor

    Hi,
    I have a scenario where I am using a thread pool executor to submit threads. and then, I am waiting at the end for all threads to finish using below code.
    threadPoolExecutor.shutdown();
    try {
    while (!threadPoolExecutor.awaitTermination(1000L, TimeUnit.MILLISECONDS)) {
    // awaiting termination of all the threads here.
    What I required is, I want to catch the exceptions that are been thrown by one of the threads in ThreadPoolExecutor in my method where I am submitting threads and want to do some processing based on those exceptions.
    Is it possible to catch those exceptions that are been thrown by the threads in ThreadPoolExecutor? If so, can some one please let me know how to do that?
    Thanks
    Pallavi
    Here is sample code:
    import java.io.IOException;
    import java.util.concurrent.Callable;
    import java.util.concurrent.Future;
    import java.util.concurrent.ThreadPoolExecutor;
    import java.util.concurrent.TimeUnit;
    public class sample2 { 
    ThreadPoolExecutor threadPoolExecutor = null;
    public sample2()
    super();
    threadPoolExecutor = new ThreadPoolExecutor(5,10,5,TimeUnit.MINUTES, new ArrayBlockingQueue(10));
    public static void main(String[] args) throws IOException
    sample2 s = new sample2();
    s.checkThreadPoolExecutor();
    System.out.println("I am done with calling all threads- waiting for threads to finish");
    s.threadPoolExecutor.shutdown();
    try {
    while (!s.threadPoolExecutor.awaitTermination(1000L, TimeUnit.MILLISECONDS)) {
    // awaiting termination of all the threads here.
    catch(Exception e)
    System.out.println("Exception while waiting fot threads to finish");
    s.threadPoolExecutor.shutdown();
    System.out.println("Bye bye");
    public class TestThread implements Callable<Integer>
    int i =0;
    String sample = null;
    public TestThread(int i)
    this.i = i;
    @Override
    public Integer call() {
    System.out.println("I am thread-"+i + "and sleeping for 1 min");
    try
    Thread.sleep(1000*5);
    catch(InterruptedException ie)
    System.out.println("some one woke me up");
    try{
    String test = sample.substring(0,1);
    catch(Exception e)
    throw new RuntimeException(e);
    return i;
    private void checkThreadPoolExecutor()
    for(int i = 0; i <10;i++)
    testMethod(i);
    System.out.println("I am done with i:" + i + " in checkThreadPoolExec");
    private void testMethod(int i)
    TestThread thread = new TestThread(i);
    Future<Integer> future = threadPoolExecutor.submit(thread);
    Edited by: Pallavi.Palleti on Feb 17, 2009 7:41 PM

    Hi,
    some hints for future postings:
    - use code-tags when submitting code (tags are available at icon bar at the top of your message editor); this will make your code easier to read given you preserved proper indentation when copying it to your posting
    - class names should start with an upper case letter (e.g. "public class Sample2" instead of "public class sample")
    - you do not submit "Threads" to an executor, you either submit Runnables or Callables; Threads are pooled inside the executor to execute the Runnables/Callables you submit
    As for your question: where exactly do you want to handle the exception? Within your Runnable or when checking the result of the Future? For the second case, Future.get() should throw an ExecutionException if the underlying Runnable/Callable threw an exception.
    In general, there is the concept of an UncaughtExceptionHandler that will take care of any execptions that occur and have not been handled by the corresponding implementation.
    Bye.

  • ThreadPoolExecutor constructor

    The thread pool executor takes a blocking queue as its argument (i.e. the work queue) which according to the API’s is used for +“… holding tasks before they are executed”+
    If a thread pool executor is permitted a maximum of 2 threads and has a fixed size work queue of 1 ….. if the main thread calls submit() twice before one of the pooled threads has a chance to execute will this result in the second call to submit() throwing an exception because of the size of the work queue being exceeded?
    I’m just slightly confused by the following description from the API:
    +•     If fewer than corePoolSize threads are running, the Executor always prefers adding a new thread rather than queuing.+
    +•     If corePoolSize or more threads are running, the Executor always prefers queuing a request rather than adding a new thread.+
    +•     If a request cannot be queued, a new thread is created unless this would exceed maximumPoolSize, in which case, the task will be rejected.+
    As +“fewer than corePoolSize threads are running”+, i.e. no threads are running, does the work queue actually get used (and so is its size relevant)?

    submit() on ThreadPoolExecutor will call execute this code:
        public Future<?> submit(Runnable task) {
            if (task == null) throw new NullPointerException();
            RunnableFuture<Object> ftask = newTaskFor(task, null);
            execute(ftask);
            return ftask;
        }That code will then call execute that is implemented like this in ThreadPoolExecutor:
        public void execute(Runnable command) {
            if (command == null)
                throw new NullPointerException();
            if (poolSize >= corePoolSize || !addIfUnderCorePoolSize(command)) {  // 1
                if (runState == RUNNING && workQueue.offer(command)) { //2
                    if (runState != RUNNING || poolSize == 0)
                        ensureQueuedTaskHandled(command);
                else if (!addIfUnderMaximumPoolSize(command)) // 3
                    reject(command); // is shutdown or saturated // 4
        }addIfUnderCorePoolSize at 1 will return false since it can't create a new thread (you had already created two threads)
    workQueue.offer at 2 will return false since we already had placed one item in the bound queue and can't add a new item right now
    addIfUnderMaximumPoolSize will also return false since we can't create a new thread
    reject at 4 will then be executed
    Kaj

  • How to reference running tasks in ThreadPoolExecutor?

    Hi all!
    So this is a scenario: Thread pool size is 10 and there were 100 submitted callables)
    threadPoolExecutor.submit(callable); // times 100Assuming that the tasks are still running, how do I find out which callables are currently being executed?
    Thanks,
    Andre

    You're never going to get that because it's implementation-specific. It could be that the implementation doesn't even have it on a java thread but is using native threads to handle the execution. I'm not certain of all the rules of the specs but I'm sure there's enough leeway that a method which tells you which ones are on separate threads would eliminate optimization techniques.
    What you CAN do is make your callable class have method which tell you if it's executing or not.
    public class MyCallable implements Callable
         private volatile boolean isRunning = false;
         public void call() throws Exception
             try
                        ...open a lock...
                        isRunning = true;
                        ...close lock...
              finally
                        ...open a lock...
                        isRunning = false;
                        ...close lock...
         public boolean isRunning()
              boolean isRunningTmp = false;
                   ...open a lock...
                       isRunningTmp = isRunning;
                   ...close lock...
              return isRunningTmp;
    }

  • Using ThreadPoolExecutor, wish to obtain thread for known runnable object

    My problem is this:
    I use a ThreadPoolExecutor with default ThreadFactory to create a pair of threads; one operates a live particle simulation, the other mouse interactions with the particles.
    I would like to be able to stop one particle simulation (which is a class extending Runnable) and replace it with another. The problem is that I call myRunnableSimulator.stop(), but then I am unable to join() its thread before creating the new particle simulator, because the ThreadPoolExecutor uses a ThreadFactory. And since I have 2 threads running, Thread.currentThread() isn't much use.
    ThreadedPoolExecutor.awaitTermination(long duration, TimeUnit unit) doesn't help me either, since it waits for all tasks to terminate. I could set the timeout to some duration that feels safe for the thread I want to die to do so, but it's a bit of a fudge.
    Any advice would be much appreciated.

    If the tasks you submit to an executor have termination dependencies then you need to explicitly code them into the task based on its state, not the state of the thread executing the task.
    Thread.join() is a lazy way to asking "has my task finished execution". And it tells you nothing about the success or failure of that execution. myTask.isDone() is what you need - whether isDone comes from a Future or from your own task implementation.

Maybe you are looking for

  • Copy from Quotation to sales order

    As i try to create SO in reference to Quotation , its going again for availability check which i dont want to happen . Although in some cases we are creating direct SO without Quot reference so i need availability check to carry for SO in such case .

  • How to design rows and columns in sapscript layout

    Hi friends, Please let me know how to design rows and columns in sapscript layout with example? Thanks, Yogesh

  • How do I make a line fade?

    http://bhbws.com/images/line_fade.png How can I get a line to fade out at the bottom like this one does?  I know how to add the dropshadow but it doesn't fade out at the bottom.... TIA

  • IOS 5 renamed most of songs artist on devices

    I updated my iPhone 4 and my iPad first generation to iOS 5.  Now most all of my music songs and video's have been renamed to one artist instead of the individual artists on BOTH devices.  Each device named the artists to a different one.  Example...

  • Why not let us pin protect apps?!?!?!?

    I know this has been posted in the past, but I would love to be able to pin protect any app I choose on my iPad.  My nine year old daughter uses my iPad regularly and I would love to be able to prevent her from using any app I choose.  HBO Go is awes