Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4061818
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T15:31:11+00:00 2026-05-20T15:31:11+00:00

I submit some some Future tasks using a CompletionService wrapped round a 2 thread

  • 0

I submit some some Future tasks using a CompletionService wrapped round a 2 thread FixedThreadPool ExecutorService, I set then setup a loop equal to the number of tasks submitted and use completionservice.take() waiting for them all to complete or fail. Trouble is very occasionally it never finishes (but I don’t know why) so I changed the take() method to a poll(300,Timeout.SECONDS), the idea being if one task takes a longer than 5 minutes to complete that poll will fail and then eventually will get out of the loop and I can go through all the futures and call future.cancel(true) to force cancellation of the offending task.

But when I run the code and it hangs, I see the poll fails continually once every 5 minutes and no more tasks run so I assume that the two workers are deadlocked in some way and never finish, and never allow additional tasks to start. Because the timeout is 5 minutes and there were still 1000 tasks to run the time taken to break out the loop was too long so cancelled the job.

So what I want to do is interupt/force cancellation the current task if hasnt completed in 5 minutes but I cant see any way to do it.

This code sample shows a simplified version of what Im talking about

import com.jthink.jaikoz.exception.JaikozException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.*;

public class CompletionServiceTest
{
    public static void main(final String[] args)
    {
        CompletionService<Boolean>  cs = new ExecutorCompletionService<Boolean>(Executors.newFixedThreadPool(2));
        Collection<Worker> tasks = new ArrayList<Worker>(10);
        tasks.add(new Worker(1));
        tasks.add(new Worker(2));
        tasks.add(new Worker(3));
        tasks.add(new Worker(4));
        tasks.add(new Worker(5));
        tasks.add(new Worker(6));

        List<Future<Boolean>> futures = new ArrayList<Future<Boolean>>(tasks.size());
        try
        {
            for (Callable task : tasks)
            {
                futures.add(cs.submit(task));
            }
            for (int t = 0; t < futures.size(); t++)
            {
                Future<Boolean> result = cs.poll(10, TimeUnit.SECONDS);
                if(result==null)
                {
                    System.out.println("Worker TimedOut:");
                    continue;
                }
                else
                {
                    try
                    {
                        if(result.isDone() && result.get())
                        {
                            System.out.println("Worker Completed:");
                        }
                        else
                        {
                            System.out.println("Worker Failed");
                        }
                    }
                    catch (ExecutionException ee)
                    {
                        ee.printStackTrace();
                    }
                }
            }
       }
        catch (InterruptedException ie)
        {
        }
        finally
        {
            //Cancel by interrupting any existing tasks currently running in Executor Service
            for (Future<Boolean> f : futures)
            {
                f.cancel(true);
            }
        }
        System.out.println("Done");
    }
}

class Worker implements Callable<Boolean>
{
    private int number;
    public Worker(int number)
    {
        this.number=number;
    }

    public Boolean call()
    {
        if(number==3)
        {
            try
            {
                Thread.sleep(50000);
            }
            catch(InterruptedException tie)
            {

            }
        }
        return true;
    }
}

Output

Worker Completed:
Worker Completed:
Worker Completed:
Worker Completed:
Worker Completed:
Worker TimedOut:
Done
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-20T15:31:12+00:00Added an answer on May 20, 2026 at 3:31 pm

    I think Ive solved it, basically if a timeout occurs I then iterate through my list of future objects and find the first one that has not completed, and force cancellation. Doesn’t seem that elegant but seems to work.

    Ive changed size of pool just to show output that better demonstrates the solution but works with 2 threaded pool as well.

    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.Date;
    import java.util.List;
    import java.util.concurrent.*;
    
    public class CompletionServiceTest
    {
        public static void main(final String[] args)
        {
            CompletionService<Boolean>  cs = new ExecutorCompletionService<Boolean>(Executors.newFixedThreadPool(1));
            Collection<Worker> tasks = new ArrayList<Worker>(10);
            tasks.add(new Worker(1));
            tasks.add(new Worker(2));
            tasks.add(new Worker(3));
            tasks.add(new Worker(4));
            tasks.add(new Worker(5));
            tasks.add(new Worker(6));
    
            List<Future<Boolean>> futures = new ArrayList<Future<Boolean>>(tasks.size());
            try
            {
                for (Callable task : tasks)
                {
                    futures.add(cs.submit(task));
                }
                for (int t = 0; t < futures.size(); t++)
                {
                    System.out.println("Invocation:"+t);
                    Future<Boolean> result = cs.poll(10, TimeUnit.SECONDS);
                    if(result==null)
                    {
                        System.out.println(new Date()+":Worker Timedout:");
                        //So lets cancel the first futures we find that havent completed
                        for(Future future:futures)
                        {
                            System.out.println("Checking future");
                            if(future.isDone())
                            {
                                continue;
                            }
                            else
                            {
                                future.cancel(true);
                                System.out.println("Cancelled");
                                break;
                            }
                        }
                        continue;
                    }
                    else
                    {
                        try
                        {
                            if(result.isDone() && !result.isCancelled() && result.get())
                            {
                                System.out.println(new Date()+":Worker Completed:");
                            }
                            else if(result.isDone() && !result.isCancelled() && !result.get())
                            {
                                System.out.println(new Date()+":Worker Failed");
                            }
                        }
                        catch (ExecutionException ee)
                        {
                            ee.printStackTrace(System.out);
                        }
                    }
                }
           }
            catch (InterruptedException ie)
            {
            }
            finally
            {
                //Cancel by interrupting any existing tasks currently running in Executor Service
                for (Future<Boolean> f : futures)
                {
                    f.cancel(true);
                }
            }
            System.out.println(new Date()+":Done");
        }
    }
    
    class Worker implements Callable<Boolean>
    {
        private int number;
        public Worker(int number)
        {
            this.number=number;
        }
    
        public Boolean call()
            throws InterruptedException
        {
            try
            {
                if(number==3)
                {
                    Thread.sleep(50000);
                }
            }
            catch(InterruptedException ie)
            {
                System.out.println("Worker Interuppted");
                throw ie;
            }
            return true;
        }
    }
    

    Output is

    Invocation:0
    Thu Mar 10 20:51:39 GMT 2011:Worker Completed:
    Invocation:1
    Thu Mar 10 20:51:39 GMT 2011:Worker Completed:
    Invocation:2
    Thu Mar 10 20:51:49 GMT 2011:Worker Timedout:
    Checking future
    Checking future
    Checking future
    Cancelled
    Invocation:3
    Worker Interuppted
    Invocation:4
    Thu Mar 10 20:51:49 GMT 2011:Worker Completed:
    Invocation:5
    Thu Mar 10 20:51:49 GMT 2011:Worker Completed:
    Thu Mar 10 20:51:49 GMT 2011:Done
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

No related questions found

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.