ThreadPool and FutureTask.cancel

Hi,
I have a fixed size thread pool executing a queue of tasks. The queue is larger than the number of threads in the pool. I try to cancel several running tasks using FutureTask.cancel(). At this point, I would expect to see the thread pool start executing the queued tasks in all of the thread pools threads. What I actually see is that the thread pool cancels all the tasks, creates a single new thread, and then sequentially executes all queued tasks in that one thread. It never recreates threads up to maxPoolSize for the queued tasks. Is this the correct behavior? Here is some code that reproduces the behavior I have described:
import java.util.Map;
import java.util.HashMap;
import java.util.concurrent.*;
public class ThreadPoolTest {
    public static void main(String... argv) throws Exception {
        ThreadPoolTest t = new ThreadPoolTest();
        t.runTest();
    public ThreadPoolTest() throws Exception {
    Map<Integer, Future<?>> futures = new HashMap<Integer, Future<?>>();
    public void runTest() throws Exception {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        synchronized(futures) {
            for(int i=0; i<30; i++) {
                futures.put(i, executorService.submit(new MyThread(i)));
        Thread.sleep(1*1000);
        System.out.println("Cancelling threads");
        for(int i=0; i<10; i++) {
            Future<?> f = futures.get(i);
        if(f!=null)
            f.cancel(true);
        while(((ThreadPoolExecutor)executorService).getActiveCount() > 0) {
            System.out.println("Active count = " + ((ThreadPoolExecutor)executorService).getActiveCount());
            Thread.sleep(1000);
        executorService.shutdown();
    private class MyThread implements Runnable {
        private int threadnum = -1;
        public MyThread(int num) {
            this.threadnum = num;
        public void run() {
            System.out.println("Hello " + threadnum + " " + Thread.currentThread());
            try {
                long i = 0;
                while(i<1000000000) i++;
            } finally {
                System.out.println("Removing " + threadnum);
                synchronized(futures) {
                    futures.remove(threadnum);
            System.out.println("Goodbye " + threadnum);
}Thanks,
Anthony

I replaced the tasks' loop with a sleep(20000); and lo and behold, the threads are interrupted (as expected) and, interestingly, the ActiveCount stays at 10.
Apparently, threads/slots are not eliminated if the task catches the InterrupedException and exits. If the InterruptedException is not caught by the task/runnable, is it then propagated to the executor which then decides the thread must be destroyed because it suffered an uncaught exception?
So if your task catches the InterruptedException from cancel, things work as expected. However, there is no guarantee that the task will be able to catch the exception. To mitigate this factor, you may issue a sleep(0, 1), i.e. wait for 1 nanosecond, just before your runnable exits to catch any pending InterruptedExceptions. There still is a small window where the cancel may result in a lost thread, but the window is much smaller.
Your run method looks like this now:
        public void run() {
            System.out.println("Hello " + threadnum + " " + Thread.currentThread());
            try {
                long i = 0;
                while(i<1000000000) i++;
                Thread.sleep(0, 1);
            } catch (InterruptedException ie) {
                System.out.println("Interrupted " + threadnum);
            } finally {
                System.out.println("Removing " + threadnum);
                synchronized(futures) {
                    futures.remove(threadnum);
            System.out.println("Goodbye " + threadnum);
        }

Similar Messages

  • How do I change my user name in syn? I typed in the wrong email address. And I cancelled syn thinking this may work but no luck.

    How do I change my user name in syn? I typed in the wrong email address. And I cancelled syn thinking this may work but no luck.

    You have to clear saved password for this page:
    # Open you login page (where you have to enter username and password).
    # Right click on page and select '''Page Info''' form context menu.
    # On last tab ('''Security''') there is '''View saved passwords''' button, click it and delete all saved passwords for this page.
    # Also clear all related cookies (just in case) there is button for this next to first one.

  • If i selected to "Create a new backup" and then cancelled that option but want to go back and select "Inherit backup history"; how do i go back and do that since now when i plug in my HD, that option doesn't appear anymore?? Any Help?

    If i selected to "Create a new backup" and then canceled that option but want to go back and select "Inherit backup history"; how do I go back and do that since now when I plug in my external hard drive, that option doesn't appear anymore?? Any Help? I bought a MacBook Air, but decided to return it for the newest model, and I wanted to back it up so that I can then back it up on my new MacBook Air. I didn't understand the option to Inherit or start a new back up, and therefore selected the option to create a new backup. I believe I should have selected to Inherit backup history so that when i back it up on the new MackBook Air, it appears the same as the one I'm returning.... Is there anyway that i can re-select the option to Inherit backup history for time machine?

    Thanks for sharing this link.
    I've posted a question here https://discussions.apple.com/message/22049103#22049103 describing my situation. Are you able to suggest me the right option?

  • My iPod touch shows up as a apple iPod camera but if i dont want to download the pics and press cancel it all dissappears. my ipod has been lost for 3 months and has not got the latest upgrade.

    My iPod touch shows up as a apple iPod camera but if i dont want to download the pics and press cancel it all dissappears. my ipod has been lost for 3 months and has not got the latest upgrade.

    Try:
    iOS: Device not recognized in iTunes for Windows
    or
    iOS: Device not recognized in iTunes for Mac OS X
    Otherwise wee need more informatin.

  • Cannot return to message list while in a message without clicking on "compose new message icon" and then cancelling it.

    After updating to 8.1 from 8 i cannot return to my message list from inside a message without clicking on the "compose new message" icon and then canceling out of that.
    Also, where it used to say return, it now says "Edit" and the word "Message" on the top of the screens is scruched together.
    Here is a link to a screenshot of my phone from the main messages listing.
    And here is a link to a screen shot of my phone from within a message.

    Hi Sir,
    Code snippet for reference:
    Private Sub Application_ItemSend(ByVal Item As Object, ByRef Cancel As Boolean)Handles OutlookApplication.ItemSend
    Try
       Dim SentMailItemObject As Outlook.MailItem
    SentMailItemObject = CType(Item,
    Outlook.MailItem)
    ‘Can
    we add here User property in Mail Object Reference?
     Catch ex As Exception
    MsgBox(ex.Message, MsgBoxStyle.Information)
     End Try
    End
    Sub

  • The GR value and GR cancellation value are different.

    Dear All,
    Could you please help me with ths?
    We have posted a GR and then cancel it but the values are different. Price control for material is S and there were:
    -No change to PO price
    -No material movements between 2 document postings
    -No invoices posted between time of GR posting and cancellation
    Thanks
    D.

    Hi D_777777,
    Can u explain me what is logic behiind Batch material PPValong with account assgnment
    So that I can think on it
    Regards
    Gitesh

  • HT5552 My Singapore VISA Credit card is not accepted as a valid payment card in Switzerland-.WHAT CAN I DO? WE just moved from Switzerland to Singapore and have cancelled our Swiss Creditcard...

    Our Singapore VISA Credit Card is not accepted as a valid Payment card b the Swiss APP Store…..
    We left Switzerland and therefore canceled your Swiss mastercard ….
    An idea's`

    Hi ..
    You posted in the, "Setting Up Apple Pay" community, so if you are tryiing to setup Apple Pay, be aware, it's limited to the U.S. only.
    Set up and use Apple Pay
    If it's not an Apple Pay issue, try this support article >   Can't change the country of your iTunes Store, App Store, iBooks Store, or Mac App Store account

  • I'm having trouble upgrading to ITunes v12.0.1 with Win 7. Download progress bar stalls and eventually cancels itself. Have tried Tools -- Download Only, but same result. Have been using iTunes for 3  years without difficulty

    I'm having trouble upgrading to ITunes v12.0.1 with
    Win 7. Download progress bar stalls and eventually cancels itself. Have tried
    Tools --> Download Only, but same result. Have been using iTunes for 3+
    years without difficulty; I have lots of ram, hard drive and speed.
    Thanks for your input

    One step listed in the link to "helpful" info, was (when Iooked 30 seconds ago), to search for and download the newest version of iTunes. I'm running iTunes on Win 7 machine and was prompted to update today, 10.22.2014, and did so without a problem. Having said that, however, it looks as though the latest iTunes (12.0.1.26) is finally doing what the last version refused to do, which is to actually fully populate all my playlists on my 6, but there is a hitch: 12.0.1.26 will NOT allow you to show the sidebar unless you click on "playlists," that is, you cannot keep it open all the time.
    And, when plugging the 6 into the computer, the phone icon shows up but clicking on it does nada. What does work, for some strange reason, is clicking on the tiny icon (just under the "Store" menu link at top screen) which looks much like a tiny barrel, someone's idea of external drives, I suppose. The phone then comes up, with the list of stuff on the phone just under it where the sidebar used to be. Sync is now restricted to the lower right of the screen.
    Apparently, you will also need to update your iPhone's software as well; some friends with the 4 and 4s, however, had troubles with them after upgrading. The message from Silicon Valley (I can see Apple from my backyard, ha ha) is apparently, "keep upgrading," folks, get rid of those old phones.

  • Due to our operating system we only have 32 bit, purchased lightroom 6 and download cancelled as says needs 64 bit, is there a 32 bit version i can get, otherwise need money back

    due to our operating system we only have 32 bit, purchased lightroom 6 and download cancelled as says needs 64 bit, is there a 32 bit version i can get, otherwise need money back

    thanks for that, but having tried the various options, still not managed to organize a refund, or anything for that matter, been on hold now for 25 minutes, first time was for 17 minutes, spoke to someone who was putting me thorough, to then have automated message saying issue could not be dealt with and it then hung up! been on to live chat and this was posted: -
    Chat
    24 hours a day, 7 days a week
    Chat is currently closed
    Which would be funny if i havent already spent 3 1/2 hours trying to sort this. I am really not enjoying my adobe experience, never known such a difficult company to speak to a 'live' person. Now on hold for 29 minutes and need to go out so nothing to be done now until tomorrow. If there is a real person from Adobe reading this, i would appreciate a call/direct email to get this resolved. now 31 minutes and I have to hang up as need to go!!! aarrgghhh!!!

  • HT6058 Hello I installed the 7.0.5 version iPhone 5c and it canceled the Hayiklod sharing photos between iPhone iPhone how can you fix it

    Hello I installed the 7.0.5 version iPhone 5c and it canceled the Hayiklod sharing photos between iPhone iPhone how can you fix it

    I'm guessing extremely botched translation of "iCloud", based on the phonetics.

  • I tried to import photos and then canceled it during.  Now i can't see where it's importing and it wont let me exit iPhoto.  How do i cancel import and exit?

    I tried to import photos and then canceled it during.  Now i can't see where it's importing and it wont let me exit iPhoto.  How do i locate or cancel import and exit?  I haven't been able to update anything on my computer because of this.

  • Anyone out there that can maybe help. I was using my 5s to record my meeting minutes for the first time and clicked cancel cos I wanted to continue recording and instead deleted it all! :( anyway to get it back?

    Anyone out there that can maybe help. I was using my 5s to record my meeting minutes for the first time and clicked cancel cos I wanted to continue recording and instead deleted it all! :( anyway to get it back?

    The other Allan is being facetious--you somehow found the forum for pre-2006 eMac desktop computers that gets little traffic.
    Getting you moved to the iPhone forums.

  • How do i back up to yesterdays sync? only showing this morning when i plug in and i cancelled that sync

    Yesterday whilst i was sending a text my iphone crashed and when it re-started all my text messages had gone. I performed a back up yesterday morning so i want to re-sync to that, however when i right click restore previous back up on devices it is only shwoing todayas day, and i cancelled the sync as soon as i plugged it in. can anyone tell me how i restore to yesterday?havent upgraded to ios5 yet

    You can copy the files back from the iPod and back them up once they are on your computer. If you have any iTunes Music Store purchases the transfer of purchased content from the iPod to authorised computers was introduced with iTunes 7. You'll find details in this article: Transfer iTunes Store purchases using iPod
    The transfer of content from other sources such as songs imported from CD is designed by default to be one way from iTunes to iPod. However there are a number of third party utilities that you can use to retrieve information from the iPod. This is just a small selection of what's available, you can also read reviews of some of them here: Wired News - Rescue Your Stranded Tunes
    Senuti Mac Only
    PodView Mac Only
    PodWorks Mac Only
    iPodDisk PPC Mac Only (experimental version available for Intel Macs)
    iRepo Mac & Windows
    iPodRip Mac & Windows
    YamiPod Mac & Windows
    Music Rescue Mac & Windows
    iPodCopy Mac & Windows
    There's also a manual method of copying songs from your iPod to a Mac or PC. The procedure is a bit involved and won't recover playlists but if you're interested it's available at this link: Two-way Street: Moving Music Off the iPod

  • My 4630 printer only prints the first page and then cancels

    My 4630 printer only prints the first page and then cancels the rest of the document. I have to manually choose to print one page at a time. If I try to print a document, it prints the first page and then cancels printing the rest of it. It's driving me crazy. I just bought this printer and, other than that, it works fine. I tried the HOTFIX link that was attached to a previous link as well as other microsoft updates, however, am still having no luck.

    Hi @ImaniL,
    I believe I have something that could assist with your printing issue
    My colleague, @JERENDS, has created these instructions to help with issues similar to yours, and I believe his instructions will help resolve your printing issue!
    Let me know how things go, and if that doesn't fix it, I will certainly see what else I can find for you
    Please click “Accept as Solution ” if you feel my post resolved your issue, as it will help others find the solution faster
    Click the “Kudos Thumbs Up" on the right to say “Thanks” for helping!
    **MissTeriLynn**
    I work on behalf of HP

  • HT4484 I can't change the country of the billing address. Now I'm living in another country and I cancelled the account I had registered. Now I can't update anything and they don't let me change the data. What could I do?

    I can't change the country of the billing address. Now I'm living in another country and I cancelled the account I had registered. Now I can't update anything and they don't let me change the data. What could I do?

    Of course you can update now. BTW, how exactly did you cancel this, did you contact AST or what?

Maybe you are looking for