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.

Similar Messages

  • Why does this program not stop when not highlighted.

    When I highlight the execution of this program it runs through and stops. However when I take off the highlight then the program does not quit running. I have encountered this problem on other programs as well. What causes it?
    Attachments:
    isotonic.vi ‏180 KB

    Hello,
    Thank you for contacting National Instruments.
    I took a look at your VI. I think the problem may be that you are using a Continue if True loop condition in your first While Loop. If you press the stop button wired to this condition or if an error is generated in your VI, that first loop will continue to run indefinitely. Try right clicking the loop conditional and changing it to Stop if True. You may then need to change your Less? function to a Greater? function within that same loop to preserve the intended behavior of your program
    I hope this solves your problem. If not, let me know.
    Matthew C
    Applications Engineer
    National Instruments

  • Issues with program not stopping

    I am working on this program and I cant get it to stop when I ask a question. It generates a random number and I am trying to ask the user if they want to play again, but it wont stop....no matter where I put the question. I also need help with when I get it to stop, how do I bring the program back to the beginning of the loop to start again if they want to play again? Please help....
    import java.util.*;
    import java.io.*;
    //Name of program
    public class HIGH_LOW
         //Allowing input to be made
         static Scanner console = new Scanner(System.in);
         //Main method
         public static void main(String[] args)
              //Generating a random number
              int rNum = (int)(Math.random() * 101);
              //Introduction to user
              System.out.println("WELCOME ALL to 'Guess a number between 1 and 100', enter 0 to quit.");
              //Initializing variables
              int guess = -1;
              int count = 0;
              int answer;
              //Initializing loop
              while (guess != rNum)
                   //Prompting user
                   System.out.print("\nGuess: ");     
                   //Reassigning variable
                   guess = console.nextInt();
                   count++;
                   //Conditional statements
                   //If the guess is correct
                   if (guess == rNum)
                        //Output for correct guess
                        System.out.println("CORRECT!!!, the number is: " + rNum + ", and it took " + count +
                                                       " guesses.");
                        //If guess too low
                        else if (guess < rNum)
                             //Output if guess is too low
                             System.out.println("Too low");
                        //If guess too high
                        else
                             //Output if guess is too high
                             System.out.println("Too high");
                   //Sentinel to exit
                   if (guess == 0)
                        //Action to be performed if user chooses
                        System.exit(0);          
              //System.out.println("Would you like to play again?"); I can put it here.....
              //System.out.println("Would you like to play again?"); Or here... and it won't stop.
    }

    I got it, this is what works for me... And I am learning how to write my own methods... You are correct, they are very useful!!!
    if (guess == rNum)
                        //Output for correct guess
                        System.out.println("CORRECT!!!, the number is: " + rNum + ", and it took " + count +
                                                       " guesses.");
                        System.out.println("Would you like to play again? Y/N");
                             //Assgining variable
                             playAgain = console.next().charAt(0);
                        //If they don't want to play again
                        if (playAgain == 'n' || playAgain == 'N')
                                  //Action performed
                                  System.exit(0);
                        //Reassign rNum
                        rNum = (int)(Math.random() * 101);
                        }

  • I got an error message: 'iTunes has stopped working. A problem caused the program to stop working correctly. The solution asked me to load latest version which I did many times and still not working... HELP!

    [Window Title]
    Microsoft Windows
    [Main Instruction]
    iTunes has stopped working
    [Content]
    A problem caused the program to stop working correctly. Windows will close the program and notify you if a solution is available.
    [Close program]
    This is what I got... sorry, not very tech savvy to copy the error message onto here...
    Have tried uninstalled and re-installed iTune, updated the new version of 10.6... many times over still not working!!!
    I share the frustrations of many here. HELP!!!!!

    Hi there Nok Saensanoh,
    I would recommend taking a look at the troubleshooting steps found in the article below.
    iTunes for Windows Vista, Windows 7, or Windows 8: Fix unexpected quits or launch issues
    http://support.apple.com/kb/ts1717
    -Griff W.

  • I have a program not responding in paralellels 7, how to I get it to stop.

    I have a program not responding in paralellels 7, how to I get it to stop. I am running OS 10.7.4.

    Firstly, you'll need to open up the Windows Task Manager by pressing CTRL + ALT + DELETE. From there, simply find your unresponsive program, right-click and select Go To Progress (not End Task). The Processes tab will open and your program should be highlighted. Now, press the End Process button and select Yes. It instantly closes the problem
    http://operating-systems.wonderhowto.com/how-to/quickly-force-quit-any-program-w indows-414334/

  • Hi help unlock the phone happened after we installed a new programa we can not get the activation password and ID, I know and still does not stop the phone bought in Israel and what documents should be sent to confirm that my phone Please read through the

    hi help unlock the phone happened after we installed a new programa we can not get the activation password and ID, I know and still does not stop the phone bought in Israel and what documents should be sent to confirm that my phone Please read through the help

    What I am saying is ..........
    The iPhone HAS to be active making calls on the UK carrier network for the carrier to identify as "theirs" and therefore eligible for the Carrier to unlock
    The way to achieve this is to use a PAYG sim making and receiving calls to establish a customer relationship  with the Carrier and then follow the Carrier's process to unlock
    With a PAYG it usually means adding a specified (by the carrier ) amount  usually £15 /£20 depending on the carrier
    This is how O2 function and according to Gemma  this is how Vodafone work

  • Suddenly all of my Office-programs have stopped working and will not launch on my MacBook. Could anyone give an amateur from Norway a hint of what may cause the problem? And I can not find the installation-disc for Office...Super! :)

    Suddenly all of my Office-programs have stopped working and will not launch on my MacBook. They were all already installed when I bought the computer. Could anyone give an amateur from Norway a hint of what may cause the problem? (And I can not find the installation-disc for the Office Programs...Super!)

    Have you contacted Microsoft support - http://www.microsoft.com/mac/support ? 

  • FROM WINDOWS (VISTA) A PROBLEM HAS CAUSED THE PROGRAM TO STOP WORKING CORRECTLY. WINDOWS WILL CLOSE THIS PROGRAM AND NOTIFY YOU IF THERE IS A SOLUTION. FIRE FOX UPDATED TO THE LATEEST, I WOULD RATHER NOT HAVE AUTO UPDATES.

    FROM WINDOWS (VISTA) A PROBLEM HAS CAUSED THE PROGRAM TO STOP WORKING CORRECTLY. WINDOWS WILL CLOSE THIS PROGRAM AND NOTIFY YOU IF THERE IS A SOLUTION. UPDATED TO THE LATEEST, I WOULD RATHER NOT HAVE AUTO UPDATES. [email protected] edit

    You may select how and whether Firefox updates, although like most software it may be sensible to keep it up-to-date, it is more likely to remain secure and compatible with other software whilst up to date.
    * for information on the options available see [[Updating firefox]] <--- clickable link ---

  • The completed program does not stop by itself.

    I am writing a simple vi to run a loop and also I am writing a few commands outside the loop. I am using a flat sequency structure inside a while loop. I am also writing a few commands oustide the while loop in another sequence structure box adjacent to it.
    The progrm executes and does exactly what I want, but the program does not stop running and the run button remains pressed. So because of this, when I call this VI in a bigger program the bigger program hangs when it calls the sub VI as the sub VI is not finishing. I tried using the STOP button, but when I do this, even the bigger program stops executing at this step.
    Is there any way I can stop this subVI alone.
    Thanks,
    Vijay 

    Your vi has race conditions written all over it.  You local variables are all over the place.  There is no guarantee which will happen first, the variable gets written to, or the variable gets read.  You should learn the concept of data dependency execution flow.  Use wires instead of local variables.  Use Error In and Error Out to create the execution order.  Look at the attached vi, which is a modification of your vi.  Also, if the loop exit conditions are never met (Vout is never less than 0.01 or Vin is never less than 2) then your loop will never exit.  You might want to check if these conditions will actually happen, or put a stop button to manually stop the loop and wire it into an OR function with the other conditions.
    - tbob
    Inventor of the WORM Global
    Attachments:
    UVLO[1].vi ‏44 KB

  • Photoshop CC 2014, A problem caused the program to stop working

    When opening Photoshop CC 2014, I get "A problem caused the program to stop working correctly". Works fine on my home computer but the new one in the office has the error message. I have the latest cloud version of the program. I've updated the AMD/ATI display driver- first from the HP site supporting the Win 7 Pro laptop I'm working on(driver ver.13.2) and then from the AMD site (ver.14.1) I've installed all windows updates. Still get the same message followed by Photoshop closing itself out.
    Has windows ever notified anyone of a solution

    I think once Windows notified me of a solution (which was to update my video card driver). Most of the time you don't get a direct response, but submitting the report does give the engineers something to work with in order to try to find out what is causing the problem.
    Anyway, there are about a million different things that can cause any application to return this generic error message. While you've already covered a couple of the possible solutions, there is still a ton of stuff to try. Since Photoshop is working on one computer but not the other, and knowing that Photoshop is exactly the same between both computers (assuming you are using the same version), then the question really becomes "what is different between the two computers?" Basically, shy of knowing that, we have a ton of general troubleshooting steps to give a shot at:
    Troubleshoot system errors, freezes | Windows | Adobe software

  • Problem with iTunes. I have Windows 8 on a new laptop. Installed latest version of iTunes. Can play music in My Library but when I click on Itunes Store I get the message "iTunes has stopped working. A problem caused the program to stop working correctly.

    I have a new laptop with Windows 8 as operating system. Installed latest version of iTunes ontop computer. I can play music in My Library but when I click on iTunes, I get the message " iTunes has stopped working. A problem caused the program to stop working correctly. Windows will close the program and notify if a solution is available."
    Anyone know what is the cause and if there is a resolution? Have tried to re-installing iTunes and have also tried restoring laptop to an earlier date.

    iPad not appearing in iTunes
    http://www.apple.com/support/ipad/assistant/itunes/
    iOS: Device not recognized in iTunes for Mac OS X
    http://support.apple.com/kb/TS1591
    iOS: Device not recognized in iTunes for Windows
    http://support.apple.com/kb/TS1538
    iTunes for Windows: Device Sync Tests
    http://support.apple.com/kb/HT4235
    IOS: Syncing with iTunes
    http://support.apple.com/kb/HT1386
    Apple - Support - iPad - Syncing
    http://www.apple.com/support/ipad/syncing/
    iTunes 10.5 and later: Troubleshooting iTunes Wi-Fi Syncing
    http://support.apple.com/kb/ts4062
    The Complete Guide to Using the iTunes Store
    http://www.ilounge.com/index.php/articles/comments/the-complete-guide-to-using-t he-itunes-store/
    iTunes Store: Associating a device or computer to your Apple ID
    http://support.apple.com/kb/ht4627
    Can't connect to the iTunes Store
    http://support.apple.com/kb/TS1368
    iTunes: Advanced iTunes Store troubleshooting
    http://support.apple.com/kb/TS3297
    Best Fixes for ‘Cannot Connect to iTunes Store’ Errors
    http://ipadinsight.com/ipad-tips-tricks/best-fixes-for-cannot-connect-to-itunes- store-errors/
    Try this first - Reset the iPad by holding down on the sleep and home buttons at the same time for about 10-15 seconds until the Apple Logo appears - ignore the red slider - let go of the buttons.
    This works for some users. Not sure why.
    Go to Settings>General>Date and Time> Set Automatically>Off. Set the date ahead by about a year.Then see if you can connect to the store.
     Cheers, Tom

  • So I download photoshop cc (2014) and when I go to open the program, it gives me an error message and shuts the program down. It says," A problem cause the program to stop working correctly. Windows will close the program." Can someone help me please?

    So I download photoshop cc (2014) and when I go to open the program, it gives me an error message and shuts the program down. It says," A problem cause the program to stop working correctly. Windows will close the program." Can someone help me please?

    I've got the same issue and it affects all my adobe software.  You are not alone as I have seen several postings looking for the answer to this help request.

  • Blackberry Desktop Software has stopped working. A problem has caused the program to stop...

    I have a Tour 9630 and just installed v6.0 and receiving an error window "Blackberry Desktop Software has stopped working. A problem as caused the program to stop working correctly.  Windows will close the program and notify you if a solution is available."  I have not received any message from Windows after 2 days.  Has anyone experienced this problem?  If so, I would appreciate any guidance.  I have Windows 7, if that matters. Thank you. in advance.

    Hi somewhatstock
    How far did you get with them? Did they have any ideas what might be causing the problem? Trying to work on it myself, so trying to eliminate what others might have tried. Curious why it works on my Desktop however. Losing tethering really causes problems as I rely on tethering with my laptop quite a lot.  
    Any information most welcome,
    regards,
    John

  • I can't open Itunes on my laptop. "Itunes has stopped working. A problem causes the program to stop working correctly. windows will close the program and notify you if a solution is available" is the message. what is the problem here?

    I can't open my Itunes program in my laptop computer with windows 8. the message is "Itunes has stopped working. A problem causess the program to stop working properly. windows will close the program and notify you if a solution is available". I reboot  the machine, Uninstall and re install the  Itune program, stilll the same message pops up.

    The first thing to try is System Restore to take you back to a point in time when it did work. If that is not successful, create a new user on the computer. log in with that and see if ID will start. This will tell us if the problem is in the system/program or the user account.
    If it works in a new user account, see Replace Your Preferences and in addition to replacing the prefs, empty the InDesign Recovery folder that will be in the same location and the InDesign SavedData file.

  • "iTunes has stopped working.  A problem caused the program to stop working correctly.   Windows will close the program and notify you if a solution is available."

    Whenever I connect to the iTunes store i receive an error message "iTunes has stopped working.  A problem caused the program to stop working correctly.   Windows will close the program and notify you if a solution is available."    This causes iTunes to close.  I am using iTunes version 10.5.0.142 on a Windows Vista (64) PC.  I have reinstalled iTunes selecting the "repair" option and also uninstalled and reinstalled iTunes.  Any help will be deeply appreciated.  Thank you.  Below is the result of the diagnositc.
    Microsoft Windows 7 x64 Home Premium Edition Service Pack 1 (Build 7601)
    HP-Pavilion BN474AV-ABA HPE-150t
    iTunes 10.5.0.142
    QuickTime not available
    FairPlay 1.13.35
    Apple Application Support 2.1.5
    iPod Updater Library 10.0d2
    CD Driver 2.2.0.1
    CD Driver DLL 2.1.1.1
    Apple Mobile Device 4.0.0.96
    Apple Mobile Device Driver 1.57.0.0
    Bonjour 3.0.0.10 (333.10)
    Gracenote SDK 1.9.3.494
    Gracenote MusicID 1.9.3.106
    Gracenote Submit 1.9.3.136
    Gracenote DSP 1.9.3.44
    iTunes Serial Number 002FAD94098CD0E0
    Current user is not an administrator.
    The current local date and time is 2011-11-13 22:08:54.
    iTunes is not running in safe mode.
    WebKit accelerated compositing is enabled.
    HDCP is not supported.
    Core Media is supported.
    Video Display Information
    NVIDIA, NVIDIA GeForce GT 220
    **** External Plug-ins Information ****
    No external plug-ins installed.
    Genius ID: 2cb3fff3fa771d265b0f8ffdcca13b55
    **** Network Connectivity Tests ****
    Network Adapter Information
    Adapter Name: {F4A2029C-16AA-4BDF-8DB7-9EC2A75B5991}
    Description: Realtek PCIe GBE Family Controller
    IP Address: 192.168.1.6
    Subnet Mask: 255.255.255.0
    Default Gateway: 192.168.1.1
    DHCP Enabled: Yes
    DHCP Server: 192.168.1.1
    Lease Obtained: Sun Nov 13 21:09:29 2011
    Lease Expires: Mon Nov 14 21:09:29 2011
    DNS Servers: 192.168.1.1
    Active Connection: LAN Connection
    Connected: Yes
    Online: Yes
    Using Modem: No
    Using LAN: Yes
    Using Proxy: No
    SSL 3.0 Support: Enabled
    TLS 1.0 Support: Disabled
    Firewall Information
    Windows Firewall is on.
    iTunes is NOT enabled in Windows Firewall.
    Connection attempt to Apple web site was successful.
    Connection attempt to browsing iTunes Store was successful.
    Connection attempt to purchasing from iTunes Store was successful.
    Connection attempt to iPhone activation server was successful.
    Connection attempt to firmware update server was successful.
    Connection attempt to Gracenote server was successful.
    Last successful iTunes Store access was 2011-11-13 22:02:08.
    **** CD/DVD Drive Tests ****
    LowerFilters: PxHlpa64 (2.0.0.0),
    UpperFilters: GEARAspiWDM (2.2.0.1),
    E: hp DVD A DH16ABLH, Rev 3HD9
    Data or MP3 CD in drive.
    Found 1 songs on CD, playing time 15:40 on CDROM media.
    Track 1, start time 00:02:00
    Get drive speed succeeded.
    The drive CDR speeds are: 8 16 24 32.
    The drive CDRW speeds are: 8.
    The drive DVDR speeds are: 8.
    The drive DVDRW speeds are: 8.
    The last failed audio CD burn had error code 4251(0x0000109b). It happened on drive E: hp CDDVDW TS-H653R on CDR media at speed 24X.
    **** Device Connectivity Tests ****
    iPodService 10.5.0.142 (x64) is currently running.
    iTunesHelper 10.5.0.142 is currently running.
    Apple Mobile Device service 3.3.0.0 is currently running.
    Universal Serial Bus Controllers:
    Intel(R) 5 Series/3400 Series Chipset Family USB Enhanced Host Controller - 3B34. Device is working properly.
    Intel(R) 5 Series/3400 Series Chipset Family USB Enhanced Host Controller - 3B3C. Device is working properly.
    FireWire (IEEE 1394) Host Controllers:
    VIA 1394 OHCI Compliant Host Controller. Device is working properly.
    Connected Device Information:
    Bruce's iTouch, iPod touch (2nd generation) running firmware version 4.2.1
    Serial Number: 1C9053CC201
    **** Device Sync Tests ****
    Sync tests completed successfully.

    Same exact thing with me.  And no help from apple.  Just dropped nearly $600 and cannot get a decent working setup.
    Apple's only suggestion was to uninstall iTunes and Quicktime, and re-install... of course (the I.T. Crowd tactic).
    The crash happens only on iTunes store access.

Maybe you are looking for