ExecutorService and awaitTermination

I have an executor service(MainES), which in turn starts a thread. This thread in turn use an executor service to execute(S1) say 10 threads(T1-T10). T1-T10 say sleeps for 20 secs.
My question is when I awaitTermination on the MainES, why does it return true though the threads in S1 have not completed? Why does it not wait for all the tasks in S1 to finish? They are the child threads.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class TestES {
    /** Creates a new instance of TestES */
    public TestES() {
    public static void main(String[] args) {
        TestES testEs = new TestES();
        testEs.process();
    public void process() {
        ExecutorService esMain = Executors.newCachedThreadPool();
        esMain.execute(new Handler());
        esMain.shutdown();
        boolean result=false;
        try {
            result = esMain.awaitTermination(1000, TimeUnit.SECONDS);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        System.out.println("awaitTermination? " + result);
    class Handler implements Runnable {
        Handler() {
        public void run() {
            ExecutorService es = Executors.newCachedThreadPool();
            for(int i=0;i<10;i++) {
                es.execute(new HandlerChild());
            es.shutdown();
    class HandlerChild implements Runnable {
        HandlerChild() {
        public void run() {
            // read and service request
            try {
                Thread.sleep(100);
                System.out.println("HandlerChild........"+Thread.currentThread());
            } catch (InterruptedException ex) {
                ex.printStackTrace();
}

ForumKid2 wrote:
I have two long queries that run about 30 seconds each. Without the ExecutorService it takes approximately 1 minute to get the results single threaded.
I setup the above logic to call the queries and its takes the same amount of time (give or take a few milliseconds) to return the results. In essence, the queries should run at the same time therefore taking approximately half the time which would be around 30 seconds. That's why I think I am doing something wrong.If your examples are anything to go by, you most likely do the work in the constructor. Don't do that, do the work in the call()-method. That is what it is there for. If you do the work in the constructor, the calling thread will simply do the work before adding it to the executorservice, robbing you of the benefit of that service.

Similar Messages

  • Using ExecutorService

    I just have a general opinion question for this forum.
    When is it better to use an ExecutorService for running threads vs just running new thread from a call like Thred t = new Thread().

    I use ExecutorService (and/or Executor) almost always.
    new Thread() is only useful when I want direct control over the threads and want to manage exactly which thread does what at each point in time. Which is very rare.
    ExecutorServices/Executor make it very easy to tweak the level of parallel work to be done, while keeping the actual working code completely the same, no matter if you use 2 threads, 100 threads or even do all the work on a single thread (by implementing a simple dummy-Executor that just calls run()).

  • How to design to end the threadpool program

    hi,
    I have a threadpool and submit a fixed no. of Runnables to it. But i want to know when all the submitted tasks are completed and to end the program. I don't think ending after submitting the last Runnable is a good solution. May i schedule another Runnable to check the size of the queue and end the entire program.
    Thanks.
    sorry for submitting in wrong category, should be in concurrency.
    Edited by: itsraja on Apr 14, 2010 12:43 AM

    Simply call [shutdown()|http://java.sun.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html#shutdown()] and then [awaitTermination()|http://java.sun.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html#awaitTermination(long,%20java.util.concurrent.TimeUnit)].

  • Trying to implement a mail queue

    I'm trying to implement a very basic mail queue using ExecutorService and a Callable split into a producer which builds the email and an email queue and a consumer to send the queued message out but I keep getting:
    java.lang.NullPointerException
         at javax.mail.Transport.send(Transport.java:97)
         at org.bedework.mail.sendMail.call(sendMail.java:45)
         at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
         at java.util.concurrent.FutureTask.run(Unknown Source)
         at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
         at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)
    I'm not sure how to get the transport variable passed across and read by the consumer thread.
    The consumer code is:
    public class sendMail implements Callable<Object> {
         private ArrayBlockingQueue<Object>  queuedMail;
         private Transport trans;
         private MimeMessage msg;
         private Logger log = Logger.getLogger(sendMail.class);
         public sendMail (ArrayBlockingQueue<Object> queuedMail, Transport trans) {
              this.trans = trans;
              this.queuedMail = queuedMail;
         public Object call() throws Exception {
              try {
                   queuedMail.poll();
                   synchronized (queuedMail) {
                      if (queuedMail.isEmpty()) {
                         queuedMail.wait(1000);
                   try {
                        trans.send(msg);
                        Thread.sleep(1000);
                   } catch (Exception e) {
                        e.printStackTrace();
              } catch (Exception e) {
                   e.printStackTrace();
              return null;
    }The code that calls it is:
    tr = sess.getTransport(config.getProtocol());
            pool.submit(new buildMail(sess, cal, originator, to, subject));
            pool.submit(new sendMail (mailqueue, tr));I'd be grateful for any pointers in getting this sorted out.

    First, read this FAQ item:
    [http://java.sun.com/products/javamail/FAQ.html#send|http://java.sun.com/products/javamail/FAQ.html#send]
    Then explain to me how "msg" is ever set in your sendMail class.

  • Executors inside a container

    Hi. I need to use ExecutorService inside my application.
    Application is targeted to intensive usage and I want to take advantage of Java SE 5 concurrency.
    How can I use Executors inside Web container? Can I create ExecutorService and put it to ServletContext?
    How can I use Executors inside EJB container? Can I put it to JNDI?
    Is there any restrictions or special conditions to do this?

    Frank,
    Thanks, wasn't sure what extra information to provide but I'm running 11.1.1.3.0 of JDeveloper. If I create a two level tree data contol that works fine. When I add the third level I get the error yet I can navigate through the data control using the business components browser and the structure seems fine. I've tried two separate two level data controls; the first with the top two levels of the tree, the second with the bottom two levels of the tree. Both work fine but when I combine them into a single data control, then I get the error.
    One of the problems I have is not knowing what the error means, so I have no idea what to start looking at to determine what to do to try to remedy it.
    George

  • Is Executor thread-safe

    Hello,
    Suppose you have an Executor to execute tasks (one of the standard implementations provided by the JDK).
    Is there any risk if you have multiple threads that use the executor to submit or execute tasks?.
    In other words: Is Executor thread-safe?
    I'm not talking about the working threads that execute the tasks.
    I'm talking about the threads that send the tasks to execution.
    Thank you.

    JoseLuis wrote:
    can you please tell me where can I find that kind of facts, because I could not find it in the javadoc.Well, it isn't a requirement for ExecutorServices, but it how the implementations provided by the java.util.concurrent package operate. That fact is stated in the API for ThreadPoolExecutor in several places:
    In the class description:
    Queuing
        Any BlockingQueue may be used to transfer and hold submitted tasks.Then, all the Constructors that take work queues only take BlockingQueues, and the getQueue() method returns a BlockingQueue.
    Finally, there are only 2 implementations of the ExecutorService provided, ThreadPoolExecutor, and ScheduledThreadPoolExecutor, which subclasses ExecutorService (and does not indicate different rules for Queues).
    >
    if you can tell me about a book or official document it would be great.
    thanx again

  • Problem with GC

    Dear all;
    I write a simple code to force one of the tasks in my algorithm to work in parallel. Since the rate of creating threads are high and I create ExecutorService and a fixed pool of 5 repeatedly after a few iterations the system almost run out of memory. What is wrong with this code and how I can improve it? Remember the loop is running at list 500 times.
         for (int i = pop.length - 1; i >= 0 ; i--)
              if (totalUnique > 5)
              ExecutorService distanceExecutor = Executors.newFixedThreadPool(5);
              AntibodyDistanceChecker[] DCT = new AntibodyDistanceChecker[5];
              int step = (int) Math.floor(totalUnique / 5);
              DCT[0] = new AntibodyDistanceChecker("DCT0"+i,
                        pop,
                        Arrays.copyOfRange(bestSet, 0, step),
                        minAllowedDistance);
              DCT[1] = new AntibodyDistanceChecker("DCT1"+i,
                                                           pop[i],
                                                           Arrays.copyOfRange(bestSet, step , 2*step),
                                                           minAllowedDistance);
              DCT[2] = new AntibodyDistanceChecker("DCT2"+i,
                                                           pop[i],
                                                           Arrays.copyOfRange(bestSet, (2*step) , 3*step),
                                                           minAllowedDistance);
              DCT[3] = new AntibodyDistanceChecker("DCT3"+i,
                                                           pop[i],
                                                           Arrays.copyOfRange(bestSet, (3*step) , 4*step),
                                                           minAllowedDistance);
              DCT[4] = new AntibodyDistanceChecker("DCT4"+i,
                                                           pop[i],
                                                           Arrays.copyOfRange(bestSet, (4*step), totalUnique ),
                                                           minAllowedDistance);
              distanceExecutor.execute(DCT[0]);
              distanceExecutor.execute(DCT[1]);
              distanceExecutor.execute(DCT[2]);
              distanceExecutor.execute(DCT[3]);
              distanceExecutor.execute(DCT[4]);
                   distanceExecutor.shutdown();
                   while (!distanceExecutor.isTerminated()) {}
                   for(int m = 0; m < DCT.length; m++)
                        if(!DCT[m].getAcceptable())
                             isUnique = false;
                             break;
                   distanceExecutor = null;
                   DCT = null;
              }else
                   for(int j = 0; j < totalUnique; j++)
                        if (pop[i].HamingDistance(bestSet[j]) < minAllowedDistance)
                             //System.out.printf("Haming distance:\t%d\n" , pop[i].HamingDistance(bestSet[j]));
                             isUnique = false;
                             break;
              // check if the Ab reaches its lifespan limit or not. Also, check the feasibility of the solution.
         if (totalUnique < numBest && isUnique &&
              pop[i].getAge() < maxAntibodyLifeSpan &&
              pop[i].getAffinity(2) > 1 &&
              pop[i].getAffinity(2) < num_Attributes - 1)
              bestSet[totalUnique] = pop[i].clone();
              totalUnique++;
         isUnique = true;
    Edited by: 891039 on Oct 12, 2011 4:38 AM

    Problem is because of your continuous Fixed thread creation within the loop.
    Number of threads/process can be created per user/session is limited in almost all platforms.
    Bring out Executors.newFixedThreadPool(5); to outside of the for loop. (Many be done only once)
    Now it retains only 5 threads for the service.
    Tasks will be queued up if there is no active threads available to serve the new incoming tasks. So there will be wait over there
    If your task/objects are short lived and if you are not sure how many tasks may arrive go for Cached Thread Pool.
    This fine tunes the pool with unused threads going away from the pool and new threads created during the run time in case no active threads are present
    Edited by: 892393 on Oct 20, 2011 2:28 AM

  • Performance wise which is best extends Thread Class or implement Runnable

    Hi,
    Which one is best performance wise extends Thread Class or implement Runnable interface ?
    Which are the major difference between them and which one is best in which case.

    Which one is best performance wise extends Thread Class or implement Runnable interface ?Which kind of performance? Do you worry about thread creation time, or about execution time?
    If the latter, then don't : there is no effect on the code being executed.
    If the former (thread creation), then browse the API Javadoc about Executor and ExecutorService , and the other execution-related classes in the same package, to know about the usage of the various threading/execution models.
    If you worry about, more generally, throughput (which would be a better concern), then it is not impacted by whether you have implemented your code in a Runnable implementation class, or a Thread subclass.
    Which are the major difference between them and which one is best in which case.Runnable is almost always better design-wise :
    - it will eventually be executed in a thread, but it leaves you the flexibility to choose which thread (the current one, another thread, another from a pool,...). In particular you should read about Executor and ExecutorService as mentioned above. In particular, if you happen to actually have a performance problem, you can change the thread creation code with little impact on the code being executed in the threads.
    - it is an interface, and leaves you free to extend another class. Especially useful for the Command pattern.
    Edited by: jduprez on May 16, 2011 2:08 PM

  • Is volatile necessary for variables only accessed inside synchronized block

    Hi,
    I am using ExecutorService to execute a set of threads. Then the calling thread needs to wait until all of them are done to reuse the thread pool to run another set of threads (so I can't use the ExecutorService.shutdown() to wait for all of the threads at this point). So I write a simple monitor as below to coordinate the threads.
    My question is: will it work? someone suggests that it might not work because it will busy spin on the non-volatile int which may or may not be updated with the current value from another thread depending on the whims of the JVM. But I believe that variables accessed inside synchronized blocks should always be current. Can anyone please help me to clarify this? Really appreciate it.
         * Simple synchronization class to allow a thread to wait until a set of threads are done.
         class ThreadCoordinator{
         private int totalActive = 0;
         public synchronized void increment(){
         totalActive++;
         notifyAll();
         public synchronized void decrement(){
         totalActive--;
         notifyAll();
         public synchronized void waitForAll(){
         while(totalActive != 0){
         try{
         wait();
         }catch (InterruptedException e){
         //ignore
         }

    Don't do that. Just save the Futures returned by the ExecutorService, and call get() on them all. This will only return when all the tasks have finished.

  • Stopping scheduled task on demand

    Hello
    My client application connects server every second, that's why a put an Runnable object into scheduleAtFixedRate method and it works great. However, I put all the threads into one ExecutorService object (namely exec) and sometimes need to stop connection retries (say, when I click a button). Is there any possibility to stop scheduled thread on demand? I tried exec.remove() but it just removes task from the queue and generally speaking doesn't work.
    The only brutal solution which cames to my mind is to create another ExecutorService object, start that scheduled task into this ExecutorService and when needed just execute connectionexec.shutdownNow(). Are there any other solutions?
    thanks
    M

    did you try calling cancel on the ScheduledFuture returned by the schedule method?

  • ExecutorService using bufferwriter and printwriter

    I'm trying to create a simple multithread chat server for class. when i run the server and connet with multiple clients the server only outputs to one client. it also appears that the server will keep a running list of who sent data to the server, but will only repot back to the last connected client.
    I need help
    the java code is located at the attached link.
    [http://www.ralieghnet.com/?q=node/23]

    *** chatServer ***
    import java.net.*;
    import java.io.*;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    public class chatserver {
          private final static int maxClients = 10;
    public static void main(String[] args){
            ServerSocket sock = null;
            Socket client = null;
            ExecutorService threadExecutor = Executors.newFixedThreadPool(maxClients);
            chatServerConnections chatConnection = new chatServerConnections();
            try{
                sock = new ServerSocket(6013);
                System.out.println("Now accepting Connections");
                while(true)
                    chatConnection.chatConnections(sock.accept());
                    chatServerListener chatListen = new chatServerListener(chatConnection);
             threadExecutor.execute((Runnable) chatListen);
            catch (IOException ioe){
                System.err.println(ioe);
    }*** chatServerConnection ***
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.InetAddress;
    import java.net.Socket;
    public class chatServerConnections
    private Socket clientSocket;
    private BufferedReader input;
    private PrintWriter output;
            chatServerConnections()
               clientSocket = null;
               input = null;
               output = null;          
    public void chatConnections(Socket socket)
                clientSocket = socket;
                System.out.println(clientSocket);
                try{
                    input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    output = new PrintWriter(socket.getOutputStream());
                catch (IOException ioe)
                    System.err.println(ioe);
    public String getInput() throws IOException
                String temp;
                temp = input.readLine();
                input.reset();
                return temp;
    public void setOutput(String inString)
                output.println(inString);
                output.flush();
            public String getAddress()
                return " connected @ " + clientSocket.getLocalAddress() +" " +clientSocket.getLocalPort() +" >>";
    }*** chatServerListener ***
    import java.net.Socket;
    import java.io.*;
    class chatServerListener implements Runnable{
        private String userName = null, userInput = "";
        private chatServerFile csf;
        private chatServerConnections chatConnect;
        public chatServerListener(chatServerConnections connect) throws IOException
            chatConnect =  connect;
            csf = new chatServerFile();
        chatServerListener() {
            throw new UnsupportedOperationException("Not yet implemented");
        public void run()
            try
                if(userName == null)
                    userName = chatConnect.getInput();
                    //userName = input.readLine();
                    chatConnect.setOutput("<< User: " + userName + " connected.>>");
                    //output.println("<< User: " + userName + " connected.>>");
                    System.out.println("<< User " + userName + chatConnect.getAddress());
                    csf.addData("<< User " + userName + chatConnect.getAddress());
            catch (IOException ioe)
                System.err.println(ioe);
            try{
                while(!(userInput == null))
                    userInput = chatConnect.getInput();
                    try
                    if(!(userInput.equalsIgnoreCase("")))
                         if(userInput.equalsIgnoreCase("GetHistory"))
                          try{
                           userInput = csf.getData();
                                 if(userInput == null)
                                  userInput = "<< SERVER: Could not complete the requested action >>";
                          catch (IOException ioe)
                           System.err.println(ioe);
                         else if(userInput.equalsIgnoreCase("quit"))
                          try{
                           chatConnect.setOutput("<< Good By >>");
                              csf.addData("<< User: " +userName + " Disconnected >>");
                              //clientSocket.close();
                              break;
                          catch (IOException ioe)
                           System.err.println(ioe);
                         csf.addData("\n" +userName + ": " + userInput);
                            chatConnect.setOutput(userName +": " +userInput);
                            if(userInput != null)
                             System.out.println(userName +": " +userInput);               
                    catch (NullPointerException npe)
                     System.err.println(npe);
                     csf.closeFile();
                System.out.println("<< User: " +userName + " Disconnected >>");
                csf.closeFile();
            catch (IOException ioe)
                System.err.println(ioe);
                System.out.println("<< User: " +userName + " Disconnected >>");
                csf.closeFile();

  • Need info regarding tasks in ThreadPool, Executor and ExecutorService

    Hi all,
    I would like to know the answers for the following questions regarding tasks:
    1.How do you create a self-starting task.(the task that starts executing as soon as we create runnable object)
    2. how do we create a task which is executed outside the runnableObject
    3. If we are executing one task in a program, how many tasks are actually running in the JVM
    4. how do we know whether a task is active or not
    5. what happens when a task in in wait but no one signals it
    6. what happens when a task does not release the lock
    7. which method is used to pause a task
    8. how do we stop and restart a task
    9. if three instances of a runnable class start executing in parallel, which one terminates first.
    I was looking for the answers for the above question in java doc and few other sites, but was of no help.
    It would be great if anyone can answer these questions. That would be lot of help.
    Thanks!!

    I see nothing in your questions relating to ThreadPool or Executors.
    Sounds like a "homework" assignment.
    First thing you need to be clearer on is what is a "task". There is no pre-defined notion of "task" in Java.
    Any introductory text of multi-threading in Java will answer those questions as they apply to threads. See the FAQ for some references.
    David Holmes

  • Using ExecutorService class from java.util.concurrent package

    Dear java programmers,
    I have a question regarding the ExecutorService class from java.util.concurrent package.
    I want to parse hundreds of files and for this purpose I'm implementing a thread pool. The way I use the ExecutorService class is summarized below:
    ExecutorService executor = Executors.newFixedThreadPool(10);
            for (int i = 0; i < 1000; i++){
                System.out.println("Parsing file No "+i);
                executor.submit(new Dock(i));
            executor.shutdown();
            try {
                executor.awaitTermination(30, TimeUnit.SECONDS);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            executor.shutdownNow();However, the code snippet above creates all the 1000 threads (Dock objects) at once and loads them to the executor, and thus I'm worrying about memory leak. I haven't tested it on 1000 files yet but just on 50 small ones, and even if the program prints out "Parsing file No "+i 50 times at once, it executes normally the threads in the background.
    I guess the write way would be to keep the number of active/idle threads in the executor constant (lets say 20 if the thread pool's size is 10) and submit a new one whenever a thread has been finished or terminated. But for this to happen the program should be notified someway whenever a thread is done. Can anybody help me do that?
    thanks in advance,
    Tom

    Ok I found a feasible solution myself although I'm not sure if this is the optimum.
    Here's what I did:
            ExecutorService executor = Executors.newFixedThreadPool(10);
            Future<String> future0, future1, future2, future3, future4, future5, future6, future7, future8, future9;
            Future[] futureArray = {future0 = null, future1 = null, future2 = null, future3 = null, future4 = null, future5 = null,
            future6 = null, future7 = null, future8 = null, future9 = null};
            for (int i = 0; i < 10; i++){
                futureArray[i] = executor.submit(new Dock(i));
            }I created the ExecutorService object which encapsulates the thread pool and then created 10 Future objects (java.util.concurrent.Future) and added them into an Array.
    For java.util.concurrent.Future and Callable Interface usage refer to:
    [http://www.swingwiki.org/best:use_worker_thread_for_long_operations]
    [http://www.particle.kth.se/~lindsey/JavaCourse/Book/Part1/Java/Chapter10/concurrencyTools.html]
    I used a Future[] Array to make the code neater. So after that I submitted -and in this way filled up- the first 10 threads to the thread pool.
            int i = 9;
            while (i < 1000){
                for (int j = 0; j < 10; j++){
                    if (futureArray[j].isDone() && i < 999){
                        try{
                            i++;
                            futureArray[j] = executor.submit(new Dock(i));
                        } catch (ExecutionException ex) {
                            ex.printStackTrace();
                        } catch (InterruptedException ex) {
                            ex.printStackTrace();
                try {
                    Thread.sleep(100); // wait a while
                } catch(InterruptedException iex) { /* ignore */ }
            executor.shutdown();
            try {
                executor.awaitTermination(60, TimeUnit.SECONDS);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            executor.shutdownNow();
        }Each of the future[0-9] objects represents a thread in the thread pool. So essentially I'm check which of these 10 threads has been finished (using the java.util.concurrent.Future.isDone() method) and if yes I replenish that empty future[0-9] object with a new one.

  • ExecutorService - ShutdownNow() not shutting down

    Here is a sample application:
    On Line A, if the simple calculation is set to true, the calculations finish, and the shutdown occurs normally.
    If, however, an infinate loop is called (complex calculation), then even when calling shutdownNow() on the pool, the process never exits (which means that there's a running thread). I also tried calling future.cancel() on each task but still, the system keeps running...
    I thought that shutdownNow() was supposed to kill any running threads and terminate (?).
    package app3;
    import java.util.*;
    import java.util.concurrent.*;
    public class Sample {                                                           // CallableExample
      public static void main(String args[]) throws Exception {
        args = new String[] { "wordOne", "wordTwooooooo", "wordThree" };
        final boolean useSimpleCalculation = false;  // Line A             <---<<    // Change this to false for different behaviour
        System.out.println("Working...");
        long time0 = System.nanoTime();
        ExecutorService pool;
        //pool = Executors.newSingleThreadExecutor();
        pool = Executors.newFixedThreadPool(3);
        Set<Future<Integer>> set = new HashSet<Future<Integer>>();
        //  A. Submit work to be done - parallelize
        System.out.println("Submit work to be done - parallelizing...");
        for (String word: args) {
          // For each word in the argument list, start a new calculation task
          Callable<Integer> callable = new CallableWork(word, useSimpleCalculation);
          Future<Integer> future = pool.submit(callable);
          set.add(future);
        // B. Get and process the results
        System.out.println("Computing sum...");
        int sum = 0;
        for (Future<Integer> future : set) {
          try {
            long     timeout     = 5L;
            TimeUnit timeoutUnit = TimeUnit.SECONDS;
            sum += future.get(timeout, timeoutUnit);     // call with a 5 seconds timeout (more than enough)
          catch (ExecutionException e) {
            System.out.println("Exception: " + e.getMessage());
            System.out.println("Setting length to zero...");
            sum += 0;
          catch(TimeoutException e) {
            System.out.println("This calculation is taking too long! - How would I know which word? Too bad that Future doesn't contain the original Callable data...]");
            future.cancel(true); // Line B
        System.out.printf("The sum of lengths is:  %s%n", sum);
        long time1 = System.nanoTime();
        System.out.println("Completed in " + ((time1-time0)/1000000000L) + " seconds.");
        if (useSimpleCalculation)
          pool.shutdown(); // If you don't do this, the process never finishes because the pool is still running. Also see: pool.shutdownNow()
        else {
          //pool.shutdown();
          //pool.awaitTermination(1, TimeUnit.SECONDS);
          pool.shutdownNow(); // Line C
        System.out.println("Done.");
      // INNER CLASS
      public static class CallableWork implements Callable {
        private String word;
        private boolean simpleCalculation;
        public CallableWork(String word, boolean simpleCalculation) {
          this.word = word;
          this.simpleCalculation = simpleCalculation;
        public Integer call() {
          if (this.simpleCalculation)
            return doSimpleCalculation();
          else
            return doVeryLongRunningCalculation();
        private Integer doSimpleCalculation() {
          /*work*/ try { Thread.currentThread().sleep(2 * 1000); } catch (InterruptedException e) { ; } // continue
          return Integer.valueOf(word.length());
        private Integer doVeryLongRunningCalculation() {
          while(true) {
            // working hard here...
            Thread.currentThread().yield(); // shouldn't do this but it's just an example...
    }

    I thought that shutdownNow() was supposed to kill any running threads and terminate (?).No. Read the Javadoc.
    'Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.
    'There are no guarantees beyond best-effort attempts to stop processing actively executing tasks. For example, typical implementations will cancel via Thread.interrupt(), so if any tasks mask or fail to respond to interrupts, they may never terminate.'

  • ExecutorService - program not stopping.

    Folks,
    This program uses the ExecutorService to run some bodgy building elevator scenario test concurrently... My problem is that the program doesn't stop at the end of the run... I'm sure I could stick a System.exit(0), but that seems like "dirty" solution to me... I should be able to figure out why I've still got "heavy" thread(s) running.
    I profiled it with visual-vm and I find NO untoward threads running... leaving me totally confusterpated.
    Please if anyone could shed any light on the cause, or recommend some relevant reading, I would really appreciate it.
    Thanx. Keith.
    package forums;
    import java.util.Random;
    import java.util.List;
    import java.util.ArrayList;
    import java.util.concurrent.Callable;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;
    import java.util.concurrent.ExecutionException;
    class Lift
      private static final double SECONDS_TO_SPEED_UP_AND_SLOW_DOWN = 6.0; // original 5
      private static final double SECONDS_TO_MOVE_ONE_FLOOR = 0.75; // original 2
      private final char name;      // the name of this lift (a,b,...)
      private int floor;            // which floor is the lift currently on [1..NUM_FLOORS]
      public Lift(char name, int floor) {
        this.name = name;
        moveTo(floor);
      public char getName() { return this.name; }
      public int getFloor() { return this.floor; }
      /** returns the amount of seconds this lift will take to goto the given floor. */
      public double timeTo(int floor) {
        return SECONDS_TO_SPEED_UP_AND_SLOW_DOWN
             + Math.abs(floor-this.floor) * SECONDS_TO_MOVE_ONE_FLOOR;
      /** moves this lift to the given floor (instantly) */
      public void moveTo(int floor) {
        if ( floor<1 || floor>Building.NUM_FLOORS ) {
          throw new IllegalArgumentException("floor "+floor+" is out of range [1.."+Building.NUM_FLOORS+"]");
        this.floor = floor;
    /** The results of a TestRun */
    class Result
      final double average;
      final double worstCase;
      Result(double average, double worstCase) {
        this.average = average;
        this.worstCase = worstCase;
    /** Does a TestRun on the given number of Lift's and returns the result */
    class TestRunner implements Callable<Result>
      private static final Random RANDOM = new Random();
      private static final int NUM_LIFT_MOVEMENTS = 10*1000;
      private final int numLifts;
      private final Lift[] lifts;
      public TestRunner(int numLifts) {
        this.numLifts = numLifts;
        this.lifts = newLifts(numLifts);
      public Result call() {
        int totalTime = 0;
        double maxTime = 0;
        for (int i=0; i<NUM_LIFT_MOVEMENTS; i++) {
          int destFloor = randomFloor();
          Lift fastestLift = null;
          double fastestTime = Integer.MAX_VALUE;
          for ( Lift lift : lifts ) {
            double time = lift.timeTo(destFloor);
            if ( time < fastestTime ) {
              fastestLift = lift;
              fastestTime = time;
          totalTime += fastestTime;
          maxTime = Math.max(fastestTime, maxTime);
          fastestLift.moveTo(destFloor);
        return new Result((double)totalTime/NUM_LIFT_MOVEMENTS, maxTime);
      private static Lift[] newLifts(int numLifts) {
        Lift[] lifts = new Lift[numLifts];
        char c = 'a';
        for (int i=0; i<numLifts; i++) {
          lifts[i] = new Lift(c++, randomFloor());
        return lifts;
      private static int randomFloor() {
        return RANDOM.nextInt(Building.NUM_FLOORS) + 1;
    class Building {
      public static final int NUM_FLOORS = 160; // Burj Dubai
    }... PTO ...

    The problem was resolved by lifting the shutdownAndAwaitTermination method from the test harness of [this java.util.concurrent bugreport|http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6431315] (by none other than [Doug Lea|http://en.wikipedia.org/wiki/Doug_Lea] himself).
      public static void main (String [] args) {
        try {
          double[] averages = new double[MAX_NUM_LIFTS];
          double[] worstCases = new double[MAX_NUM_LIFTS];
          for (int t=0; t<=NUM_TIMES; t++) {
            runTest(averages, worstCases);
            System.out.format("\r%d   ", NUM_TIMES-t);
          System.out.format("\r");
          for (int n=0; n<MAX_NUM_LIFTS; n++) {
            System.out.format("for %2d lifts average was %6.2f seconds"
                , n+1, averages[n]/NUM_TIMES);
            System.out.format(" and the average worst case was %6.2f seconds%n"
                , worstCases[n]/NUM_TIMES);
          shutdownAndAwaitTermination(EXECUTOR);
          //System.exit(0);
        } catch (Exception e) {
          e.printStackTrace();
      private static void shutdownAndAwaitTermination(ExecutorService pool) {
        pool.shutdown(); // Disable new tasks from being submitted
        try {
          // Wait 10 seconds for existing tasks to terminate
          if (!pool.awaitTermination(10, TimeUnit.SECONDS)) {
            pool.shutdownNow(); // Cancel currently executing tasks
            // Wait a while for tasks to respond to being cancelled
            if (!pool.awaitTermination(10, TimeUnit.SECONDS)) {
              System.err.println("Pool did not terminate");
       } catch (InterruptedException ie) {
         // (Re-)Cancel if current thread also interrupted
         pool.shutdownNow();
         // Preserve interrupt status
         Thread.currentThread().interrupt();
    }Cheers all... and thanx anyways. Keith.

Maybe you are looking for

  • IPod touch not showing all music

    My ipod touch is not showing all of my music in 'songs', which I assumed showed all music on the device. I have about 7 Third Eye Blind songs on here and I can find all of them using the 'search ipod' tool, but only 2 of the songs show up in the musi

  • Handling error exception in timesten

    how do we handle timesten specific exception in a pl/sql block. Like TT5039...which is a exception thrown when trying to refresh a cache group using ttCacheAutoRefresh for which refresh process has already been initiated by the timesten I require to

  • Upgrade of Database with Oracle Change Data Capture

    Hello, We are upgrading and moving our database to a different server. The move is from 10G R1 database on Solaris to 11G R2 on Linux. Our database uses Oracle Change Data Capture. What is the best way to perform this migration? Unlike in the approac

  • GL Posting effects consolidation

    Do FI posting effects consolidation right away if yes, how?

  • Reading Files (simple question)

    I'm doing some homework (and no, I'm not just looking for a handout answer, I just need a simple question answered) and I was wondering about how to read a word and evaluate if the word is the same as another word. I want to do this from a .txt file