Stop threads after a certain time

I want to create a program that wants to do some work simultaneously, but each thread will return back after some time, however I do not want to wait forever so I want to stop all active threads after say 1 minute. Below is what I am doing but I am unable to stop the executing threads:
ThreadPoolExecutor tpe = new ThreadPoolExecutor(
tpSize, tpSize, 5, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
Task[] tasks = new Task[nTasks];
for (int i = 0; i < nTasks; i++) {
tasks[i] = new Task(n, "Task " + i);
tpe.execute(tasks[i]);
tpe.shutdown();
System.out.println("Done!");
try {
tpe.awaitTermination(5, TimeUnit.MILLISECONDS);
catch (Exception e) {e.printStackTrace();}
class Task implements Runnable {
long n;
String id;
private long fib(long n) {
if (n == 0)
return 0L;
if (n == 1)
return 1L;
return fib(n - 1) + fib(n - 2);
public Task(long n, String id) {
this.n = n;
this.id = id;
public void run() {
Date d = new Date();
DateFormat df = new SimpleDateFormat("HH:mm:ss:SSS");
long startTime = System.currentTimeMillis();
d.setTime(startTime);
System.out.println("Starting task " + id + " at " + df.format(d));
System.out.print("Fib: " + fib(n));
long endTime = System.currentTimeMillis();
d.setTime(endTime);
System.out.println(" Ending task " + id + " at " + df.format(d) + " after " + (endTime - startTime) + " milliseconds");
How come the threads do not stop especially when I have set a 5 Millisecond timeout?
How do I go about stopping active threads?
Message was edited by:
dawuad

I want to create a program that wants to do some work simultaneously, but each thread will return back after some time, however I do not want to wait forever so I want to stop all active threads after say 1 minute. Below is what I am doing but I am unable to stop the executing threads:
ThreadPoolExecutor tpe = new ThreadPoolExecutor(
tpSize, tpSize, 5, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
Task[] tasks = new Task[nTasks];
for (int i = 0; i < nTasks; i++) {
tasks = new Task(n, "Task " + i);
tpe.execute(tasks);
tpe.shutdown();
System.out.println("Done!");
try {
tpe.awaitTermination(5, TimeUnit.MILLISECONDS);
catch (Exception e) {e.printStackTrace();}
class Task implements Runnable {
long n;
String id;
private long fib(long n) {
if (n == 0)
return 0L;
if (n == 1)
return 1L;
return fib(n - 1) + fib(n - 2);
public Task(long n, String id) {
this.n = n;
this.id = id;
public void run() {
Date d = new Date();
DateFormat df = new SimpleDateFormat("HH:mm:ss:SSS");
long startTime = System.currentTimeMillis();
d.setTime(startTime);
System.out.println("Starting task " + id + " at " + df.format(d));
System.out.print("Fib: " + fib(n));
long endTime = System.currentTimeMillis();
d.setTime(endTime);
System.out.println(" Ending task " + id + " at " + df.format(d) + " after " + (endTime - startTime) + " milliseconds");
How come the threads do not stop especially when I have set a 5 Millisecond timeout?
How do I go about stopping active threads?
Is ThreadPoolExecutor right for me?

Similar Messages

  • Headphones stop working after a certain time and the notification for sound change has disappeared

    HP Pavilion dv6-6176sa
    Win7 64bit.
    I have a Pavilion dv6, and occasionally no sound will go through headphones when the jack is plugged in. The headphones themselves are not at fault, they are brand new and work fine.
    When the headphones are plugged in, the sound will only go through the laptop speakers. I've tried updating the drivers, fiddling with the jack and socket (as I read on google), the only resolution I have found is to restart the comp, which is a bit of a pisstake in all fairness and I'd rather not do that every time it happens.
    5 minutes ago I was watching a TV show, listening through the headphones, when I pulled out my USB mouse (and accidentally the charger with it). The sound then switched from the headphones to the speaker.
    If I open the sound settings, it will display the headphones as being plugged in, but the sound indicator bar (thingy) will only rise and fall on the speaker icon bar.
    Currently I have the audio jack pulled out about a centimetre, this allows sound through the headphones, but the sound is noticeably different to what it should be.
    I had rolled it back to "High Definition Audio Device", then reinstalled it to the most current driver. This hasn't fixed it.
    Also, this may be a related issue: (I guess) around the same time, the beats audio notification that pops up on screen when the volume is changed  has disappeared and doesn't display when the volume has changed.
    In microsoft sound control panel, it has the default speakers and the headphone logo, when i plug in the jack, a green phone circle thing appears by the headphone option, meaning it works i guess. However, the description changes from "ready" to "default communications device" and nothing changes for the regular speaker device.
    When I go to >configure, and test each (L/R) speaker, if the headphones are plugged in, the noise is louder then when they're not plugged it
    But yeah, brand new headphones, brand new laptop, it's mad. What's madder is that the headphones will work for x amount of time, then stop working when I next try to use them...

    bump...

  • Getting labview to stop after a certain time.

    I'm trying to get labview to stop running after a set time? I have a load cell attached to a NI ELVIS board and once the set load is read by labview it's outputting a voltage thourgh the board but continuesly till the load is removed. I would like to ouptut the voltage to stop after a certain amount of time with the load still on the load cell.

    bmira1 wrote:
    I would like to ouptut the voltage to stop after a certain amount of time with the load still on the load cell.
    Of course stopping LabVIEW (as described in the post title) and stopping an output voltage (as described in the post body) are two completely different things! Blindly stopping LabVIEW will not necessarily reset any active analog output to zero.
    Best would be a simple state machine that changes the output to zero after a certain elapsed time. This could for example be done with the timeout case of an event structure or even with the "elapsed time" express VI (or with the code fragments given above after you make sure there is a small wait in the polling loop)
    When the experiment starts, write a certain voltage to the output once (You don't need to do that over and over, only when the voltage changes) and, after the time has elapsed, write a zero voltage to the output.
    No need to stop LabVIEW. You should actually disable or catch "panel close?" events and other abnormal shutdown attempts, and reset the outputs in an orderly fashion before allowing the program to stop.
    LabVIEW Champion . Do more with less code and in less time .

  • IDVD is closing after a certain time.

    Hi, i made a movie with a sony Z1-HDV camera and made the montage in FCP. Than i export it with Quicktime 7.5. Than dropped it in iDVD. After a certain time iDVD just quits. With the below report.
    Also when i just open iDVD and open an other iDVD project and do nothing iDVD just quits after a certain time. Read below report.
    What to do???? I have to finish this project by wednesday!!!! HELP!!!
    Process: iDVD [512]
    Path: /Applications/iDVD.app/Contents/MacOS/iDVD
    Identifier: com.apple.iDVD
    Version: 7.0.2 (1100)
    Build Info: iDVD-11000000~17
    Code Type: X86 (Native)
    Parent Process: launchd [84]
    Date/Time: 2008-08-03 19:43:10.272 +0300
    OS Version: Mac OS X 10.5.4 (9E17)
    Report Version: 6
    Exception Type: EXCBADACCESS (SIGBUS)
    Exception Codes: KERNPROTECTIONFAILURE at 0x0000000000000000
    Crashed Thread: 22

    Yikes! You're on the very edge of a kernel panic if you haven't yet seen one. Something is amiss ....
    Are you using any external FW or USB HD's / 3rd party devices while attempting to burn an iDvd?
    If so, Restart your Mac without any 3rd party devices attached and try again. But first run apple's disc utilities to Repair Permissions. Assuming you have no less than 20GB's of available HD space on the boot volume and that all assets for iDvd are located on this same volume (your main HD and not on the external volume/s).
    Post back with your results.
    Message was edited by: SDMacuser

  • Get a waveform graph to stop plotting after a given time period

    I am doing a research project looking at the effects of modifying visual feedback on a person's current force output. I have a waveform graph that plots the target force level they are trying to match (specified by me) and next to it a second plot showing their current force output (in real time). I am trying to make a condition where the current force output plot (or really the whole waveform graph) stops plotting after a 10 s time period, but can't seem to get it to work. It either plots for the whole trial, or does not plot at all. Is there a way to put a timer on a waveform graph in order to tell it to stop plotting after a specified time period?
    Thanks!

    Hi again,
    I have tried to open the .vi you sent, but I have version 8.2 (yours is in version 8.5) and cannot open it. Is there a way for you to tave the.vi so that it can be opened with earlier versions of the program?
    I have attatched my .vi to this message as well.
    Attachments:
    bimanual combined with metronome_conds.vi ‏174 KB

  • Why do the "SAVE", "SAVE AS" and "UNDO" functions of InDesign CS6 stop working after a short time?

    Why do the "SAVE", "SAVE AS" and "UNDO" functions of InDesign CS6 stop working after a short time?

    Normally they don't. You might have some sort of problem on your system, possibly a conflict with other software, or corrupt ID prefs or application. Trashing the prefs is easy, and good place to start: Replace Your Preferences
    It will help if you tell us the OS version, whther you've installed the 8.0.1 patch, and how you are trying to access the commands, and what happens when you do. Is this isolated to one file, or does it happen with all files?

  • IPOD freezes after a certain time

    After a certain time using the device, the touch display does not work anymore. The app is still running, but not reacting any more. After switching off the Ipod is working again for a certain time.
    The device has been rebooted several times, restored via Itunes and also the firmware is up to date.
    The device is one year old, 8GByte, enough memory available and the battery charged.
    The problem started some weeks ago.
    I started to remove some apps without success actually.
    Apps that have a bigger size seem to increase the occurence of the problem
    Using WiFi increase the occurence also.
    Any ideas welcome!!!

    Here finally the solution for my problem:
    The hardware of the Ipod had a problem. The device had been replaced by a new one. As I bought the device in Germany, there is an extended warranty of 24 month. The retailer where I bought the device took it back and gave the complete money back including the shipment costs! So I ordered the now IPod Touch G4 and have now fun again.
    The suggestion which already had been given was correct and helpful.
    A comment about the retailer:
    I bought the device via Amazon. There support even on a Sunday evening was just great. In one week (!!!) I sent the device (on Monday), got the result of the investigation and received the new device (on Friday).
    The support I received here was just great!

  • Do notes disappear after a certain time?

    The earliest entry in the Notes app has disappeared. Do they get deleted after a certain time or if I have inadvertantly deleted it can i get it back from icloud somehow?

    They never expire - at least from iCloud.  I still have some five year old notes.

  • Do notes go away after a certain time?

    Do notes on the iphone4 go away after a certain time?  One of my most important note is gone.

    How old are you? If 1998 is the year you were born, it's entirely possible your parents have subscribed to a 'smart limits' service, which will disable your data connection, text messaging, etc. during hours they choose.

  • Why does my iTunes stop playing after a certain amount of time?

    When I begin a Playlist in iTunes on my 2009, 24 in. display iMac, it will suddenly stop playing after a few songs. I have looked through
    every setting I can locate, but am unable to correct this problem. Has anyone else encountered this problem?

    On the webite for the station. look for a Listen link for another type of player.  Many stations are going away from streams that iTunes can link to.  while you're on the website. look for a Contact Us llink and report your trouble.   They might not be aware there is trouble.
    Do a Get Info, go to first tab and Edit URL.. Copy and paste the stream URL here so others can test it.

  • Powershell- FTP Script to copy files only after a certain time

    Hey guys,
    We are currently running an FTP script that decrypts pgp and copies/moves several files to different archived and production locations. These files come in constantly throughout the day and we need to ensure a certain 8 files get moved to 4 different locations
    but NOT before a certain time.
    Ex: File1 and File2 are received EARLY along with 50 other files and decrypted at 9pm EST on 9/4. File1 and file2 need to WAIT to be moved until after 12:05am EST on 9/5 or it is slapped with an incorrect $date/time and not processed correctly but
    every other file needs to be moved (which is currently all configured).
    Right now, both file1 and file2 are being moved as the script runs  (every 10 minutes) so when the files come in early from the vendor- they get the incorrect date/time stamp.
    I'm fairly new to powershell so I'm not quite sure how to set this up to only move the file if it is between a certain time- say 12am-1am and no other time.

    I was able to resolve this myself by doing the following:
    $hourdate = get-time –uformat “%H” 
    #Copy-Item as long as time is in the 12:00am or 1am hour 
    if(($hourDate -eq "0")-or ($hourdate -eq "1")) 
    copy-item objects
    Thanks guys

  • Call quality gets choppy after a certain time

    Hello, Having an issue with my Comcast phone service.  Quality seems to be good (for VOIP) on most calls, however, if I have a call that runs over 45 minutes or so, the line gets choppy and I'm only able to hear about 1 out of every 3 words.  This happens consistenty on longer calls after a certain period of time (usually after around 45 minutes).  There doesn't seem to be any problem at all during shorter calls, but it's incredibly annoying since I use my phone for work and many of my work calls run longer. Thanks,Ryan

    Group video calls have a fair usage policy so if you are doing a group video call more than 4 hours a day/100 hours a month then you could have issues.  Normal video calls should not have that limitation though I could imaging there could possibly be a limitation if you attempted to keep a single video call running 24x7x365.
    http://www.skype.com/en/legal/gvc-fair-usage/

  • Firefox stops working after a short time of running, I keep getting a Net Error message

    I am very frustrated with Firefox! I can load firefox fine in the morning, but after a short time it quits working & I get a Net Error message. I notice it most on Facebook! When I click like, it won't do nothing but sut there working, if open in a new tab, I get the net error message. I try to open other websites & get the net error message. I checked & I am running the latest version. I am running fine on IE, but I like Firefox! I've been using it for years with no problems, but after an update is when I started experiencing problems. I waited thinking, firefox will fix it with another update, but no fix! I am running Windows 7 on a Gateway computer & have had no problems with older versions of Firefox. I'm sending all this information via Internet Exployer since Firefox won't work!

    Your above posted system details show outdated plugin(s) with known security and stability risks that you should update.
    *Next Generation Java Plug-in 1.6.0_17 for Mozilla browsers
    Update the [[Java]] plugin to the latest version.
    *http://www.oracle.com/technetwork/java/javase/downloads/index.html (Java Platform: Download JRE)
    Create a new profile exclusively for the 4.0 beta version and create a desktop shortcut with -P "profile" appended to the target to launch that profile.
    * http://kb.mozillazine.org/Testing_pre-release_versions
    * http://kb.mozillazine.org/Creating_a_new_Firefox_profile_on_Windows
    * http://kb.mozillazine.org/Shortcut_to_a_specific_profile
    * http://kb.mozillazine.org/Using_multiple_profiles_-_Firefox

  • BridgeVIEW Networking stops after a certain time

    Hi,
    We have a BridgeVIEW v2.1.1 system with several server PC's which are
    connected over the network with one client PC.
    The server PC's are responsable for the I/O's and the client PC is used for
    monitoring the measurements and to control the settings for the process. In
    total we have over 4000 tags in the system. A lot of them are network tags.
    If we startup the BridgeVIEW engines it all runs fine but after a while the
    network communication stops. We had this problem already in the v2.1 of
    bridgeVIEW after we installed some bug fixes which we got from NI. After
    reinstalling the v2.1 without the bug fixes the network communication was
    running OK.
    We hoped that the latest version 2.1.1 solved all our probl
    ems we have with
    it since a long time.
    Does any other user of BridgeVIEW have the same experience and is there a
    solution?
    regards, Dennis Motshagen
    INCAA Computers BV
    www.incaacomputers.com
    tel. +31-55-5425001
    fax. +31-55-5429000

    Hi,
    Please apply the following patch to your BV 2.1.1.
    ftp://ftp.ni.com/support/bridgeview/BV21%20fixes/BV%20Networking%20Patch/
    If the problem persists after applying the patch, please get in touch with
    our Support team at: [email protected]
    Regards,
    Khalid
    "Dennis Motshagen" wrote:
    >Hi,>>We have a BridgeVIEW v2.1.1 system with several server PC's which are>connected
    over the network with one client PC.>The server PC's are responsable for
    the I/O's and the client PC is used for>monitoring the measurements and to
    control the settings for the process. In>total we have over 4000 tags in
    the system. A lot of them are network tags.>If we startup the BridgeVIEW
    engines it all runs fine but after a while the>network communica
    tion stops.
    We had this problem already in the v2.1 of>bridgeVIEW after we installed
    some bug fixes which we got from NI. After>reinstalling the v2.1 without
    the bug fixes the network communication was>running OK.>>We hoped that the
    latest version 2.1.1 solved all our problems we have with>it since a long
    time.>>Does any other user of BridgeVIEW have the same experience and is
    there a>solution?>>regards, Dennis Motshagen>INCAA Computers BV>www.incaacomputers.com>tel.
    +31-55-5425001>fax. +31-55-5429000>>>

  • Why do some YouTube videos stop playing after a short time?

    Since sometime in October, 2013, I have noticed that more and more YouTube videos stop playing within a minute of starting. Most that stop do so in 15 or 16 seconds. The playing stops because the download stops. I watch this on a network activity monitor I always have running. Not all videos do this, but the problem is becoming more and more frequent. Some videos which played correctly for me in the recent past are now exhibiting this problem.
    Other than installing the latest Firefox updates I have NOT changed the software on my machine. I run Linux by the way. I do not think this is a Linux problem because (1) it was all working before and (2) my son who runs both Mac OS X *and* Windows is also seeing the same problem. We both use Firefox as our browser on all our platforms.
    I should also note that I am NOT seeing this problem with any of the other video websites I use, only when I go to YouTube. That leads me to believe that the problem is not in Firefox; if it were it should affect videos from all websites.
    Additionally the problem occurs whether or not I log into YouTube.
    I have not run Firefox in safe mode because all the extensions I use did not affect the download of Videos before, so I don't expect unchanged extensions to suddenly start causing problems.
    So, anyone else see this problem? (There was another note which talked about the same problem but it was disabled.)
    Also -- pardon my paranoia, but -- I need to ask: Since YouTube is owned by Google and Google has its own browser it wants you to use, Chrome, is it possible that Google is intentionally causing some YouTube videos to fail if it sees that they are being sent to Firefox?
    (That is not so outlandish I think. Microsoft WAS at one point caught mangling web pages going to certain web browsers other than IE. And these days Google wants to dominate the Internet just as badly as Microsoft does, so why not pull dirty tricks too?)
    If this keeps happening I am going to have to try Google's Chrome to see if it somehow manages to play YouTube videos correctly while Firefox does not. But I really do NOT want to install Chrome because I trust Google about as much as I trust Microsoft, which is to say Not At All.
    Thanks in advance.

    Hello,
    There have been some issues with Flash 11 in the recent past. This could be a manifestation of that issue. Kindly check this response below to see if this helps you in viewing Flash videos.
    Also, if you want to check if this is a flash problem and specifically on youtube, you can try the HTML5 version of Youtube. In this, there are no plugins involved, and the browser natively renders the videos. You can signup for the HTML5 trial by visiting http://youtube.com/html5. Please try that and check if the issue goes away.
    Also, in this case, Google might not be doing anything sinister - they generally try to be standards compliant too. You can definitely try installing Google Chrome and test this issue, but we definitely would want you to continue to be a Firefox user :)
    <hr>
    Some problems with Flash video playback can be resolved by disabling hardware acceleration in your Flash Player settings. (See [[Flash Plugin - Keep it up to date and troubleshoot problems|this article]] for more information on using the Flash plugin in Firefox).
    To disable hardware acceleration in Flash Player:
    #Go to this [http://helpx.adobe.com/flash-player/kb/video-playback-issues.html#main_Solve_video_playback_issues Adobe Flash Player Help page].
    #Right-click on the Flash Player logo on that page.
    #Click on '''Settings''' in the context menu. The Adobe Flash Player Settings screen will open.
    # Click on the icon at the bottom-left of the Adobe Flash Player Settings window to open the Display panel. <br/> <br/>[[Image:fpSettings1.PNG]] <br/>
    # Remove the check mark from '''Enable hardware acceleration'''.
    # Click '''Close''' to close the Adobe Flash Player Settings Window.
    # Restart Firefox.
    This [http://www.macromedia.com/support/documentation/en/flashplayer/help/help01.html Flash Player Help - Display Settings page] has more information on Flash Player hardware acceleration, if you're interested.
    <hr>
    Also, try this one too
    Recent crashes of certain multimedia contents (this includes Youtube videos, certain flash games and other applications) in conjunction with Firefox are most probably caused by a recent Flash update and/or a malfunctioning browser plugin such as Real Player.
    In order to remedy the problem, please perform the steps mentioned in these Knowledge Base articles:
    * [[Flash Plugin - Keep it up to date and troubleshoot problems]]
    * [[Flash 11.3 crashes]]
    * [[Flash 11.3 doesn't load video in Firefox]]
    Other, more technical information about these issues can be found under these Links:
    * http://forums.adobe.com/thread/1018071?tstart=0
    * http://blogs.adobe.com/asset/2012/06/inside-flash-player-protected-mode-for-firefox.html
    Please tell us if this helped!

Maybe you are looking for