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 8740057
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T11:03:48+00:00 2026-06-13T11:03:48+00:00

I have an unbounded queue of jobs which can be processed asynchronously. The processing

  • 0

I have an unbounded queue of jobs which can be processed asynchronously. The processing of each job may or may not trigger the creation of new jobs for this queue.

I would like a pool of several worker threads to take items from this queue and process them in parallel, until both the queue is empty and all worker threads are idle waiting for new jobs on the queue (as a busy worker could end up adding new jobs to the queue).

Is there a recipe for using the java.util.concurrent implementations which I can use to solve this particular problem, where workers are also producers? It is not clear that such a scenario is supported in a straightforward manner from the APIs.

In particular, I want to be able to detect the termination condition, namely, when no more jobs are available (empty job queue) and there will be no more jobs produced (all idle worker threads).

EDIT

Nam San’s answer below appears to be the most elegant approach, which basically boiled down to tracking the number of submitted jobs vs. the number of completed jobs, and using the case where these numbers were equal as the termination condition.

I’ve implemented a full example using java.util.concurrent implementations which extends ThreadPoolExecutor to achieve this, plus specialises the job queue to accept Comparable instances which are sorted in a particular way.

  • TestExecutor.java: A custom executor which extends ThreadPoolExecutor but has additional methods to execute jobs which may create new jobs, and a new await method which waits until all submitted jobs are complete.
  • WorkUnit.java: An example of a comparable, runnable job which may create new jobs to submit to TestExecutor.
  • Test.java: Contains a main method to run an example using WorkUnit instances with a TestExecutor.
  • 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-06-13T11:03:49+00:00Added an answer on June 13, 2026 at 11:03 am

    The code below demonstrates how you could use a wrapper class around an Executor to count the number of submitted jobs and compare it to the number of completed jobs to achieve what you want. Note that your tasks must call the execute method of the wrapper class and never call the underlying Executor directly. It should be trivial to extend the wrapper below to wrap the ‘submit’ methods of an ExecutorService if needed.

    public class ExampleExecutor {
    
        private final Executor executor;
        private long submitCount = 0;
        private long doneCount = 0;
    
        public ExampleExecutor(Executor executor) {
            this.executor = executor;
        }
    
        public synchronized void execute(Collection<Runnable> commands) {
            for (Runnable command : commands) {
                execute(command);
            }
        }
    
        public synchronized void execute(final Runnable command) {
            submitCount ++;
    
            executor.execute(new Runnable() {
                public void run() {
                    try {
                        command.run();
                    } finally {
                        synchronized (ExampleExecutor.this) {
                            doneCount++;
                            if (doneCount == submitCount) {
                                ExampleExecutor.this.notifyAll();
                            }
                        }
                    }
                }
            });
        }
    
        public synchronized void awaitCompletion() throws InterruptedException {
            while (doneCount != submitCount) {
                this.wait();
            }
        }
    }
    

    EDIT: Added test case below to demonstrate how the above code can be used

    public class Test {
    
        static class Task implements Runnable {
            private final String id;
            private final long repetitions;
            private final long respawnSize;
            private final ExampleExecutor executor;
    
            public Task(String id, long repetitions, long respawnSize, ExampleExecutor executor) {
                this.id = id;
                this.repetitions = repetitions;
                this.respawnSize = respawnSize;
                this.executor = executor;
            }
    
            public void run() {
                for (int i = 0; i < respawnSize; i ++) {
                    // Spawning new sub tasks
                    executor.execute(new Task(id + "-" + i, repetitions/2, 0, null));
                }
    
                double sum = 0;
                for (int i = 0; i < repetitions; i++) {
                    sum += Math.sin(i);
                }
    
                System.err.println(id + " completed at " + System.currentTimeMillis() + " with sum=" + sum);
            }
        }
    
        public static void main(String argv[]) throws InterruptedException {
            ExampleExecutor executor = new ExampleExecutor(Executors.newFixedThreadPool(2));
            executor.execute(new Task("0", 2000000, 100, executor));
    
            System.err.println("main thread awaits completion");
            executor.awaitCompletion();
            System.err.println("main thread recieved completion event");
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Is it possible to have a generic constraint which is an unbounded generic type?
I have a file, in which each line contains several words that are separated
I have a ThreadPoolExecutor that is constructed with an unbounded queue (LinkedBlockingQueue) and a
If I use unbounded wildcard types for two collections (each collection will have a
I have been searching on this for hours and can not figure out the
I have a Java code where the return type of a function has unbounded
have written this little class, which generates a UUID every time an object of
Have a procedure which looks like Procedure TestProc(TVar1, TVar2 : variant); Begin TVar1 :=
I've implemented something similar to consumer-producer problem using a unbounded linked blocking queue. I
I have a question about retrieving data values which are sent from a web

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.