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

  • Home
  • SEARCH
  • 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 6322243
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T16:17:45+00:00 2026-05-24T16:17:45+00:00

public class MainClass { private static final int size = 5; private ExecutorService prodExec

  • 0
public class MainClass {

private static final int size = 5;

private ExecutorService prodExec = Executors.newFixedThreadPool(size);
private ExecutorService consExec = Executors.newFixedThreadPool(size);

//main method here

public void start(String[] args) {

    for (int index = 0; index < size; index++) {
        Runnable producer = new Producer(consExec, listOfIds);
        prodExec.execute(producer);
    }

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            prodExec.shutdown();
            try {
                prodExec.awaitTermination(10, TimeUnit.SECONDS);
            } catch (InterruptedException ignore) {
            }

            consExec.shutdown();
            try {
                consExec.awaitTermination(10, TimeUnit.SECONDS);
            } catch (InterruptedException ignore) {
            }
        }
    });
    }
}
public class Producer implements Runnable {

private ExecutorService consExec;
private List<Long> list;

public Producer(ExecutorService exec, List<Long> list) {
    this.consExec = exec;
    this.list = list;
}

public void run() {
    for (Long id: list) {
        data = get data from db for the id
        consExec.execute(new Consumer(data));
    }
}
}
public class Consumer implements Runnable {

public void run() {
    // call web service
}
}

I would like to handle the scenario when a user requests a shutdown may be by pressing Ctrl+C. I think this could be done in the shutdown hook. However, as in the above code, each Producer gets a list of IDs (250 may be?) to process i.e., call the db to retrieve data for the ID and submit the data to the consumer thread, which then calls out to a web service.

How do I break out of the for loop in each of the Producer thread, when a shutdown has been requested so that each thread does not process the ids that haven’t been processes yet? I was able to get the shutDownHook to work, but not sure how each thread should incorporate the logic within the run method to exit the run() method in case of a shutdown request. May be by setting a boolean variable(AtomicBoolean) externally that each thread checks in the for loop before processing every id?

As I understand it, if I call shutdown(), it executes all the submitted tasks and then finishes. In this case, there is no way of stopping processing as the tasks have already beeb queued on the executor service.

If I call shutdownNow() instead of shutdown() it might produce unexpected results?

  • 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-24T16:17:46+00:00Added an answer on May 24, 2026 at 4:17 pm

    shutdownNow vs shutdown depends on if you want the currently running tasks to complete first.

    If you want them to stop immidiately you would do two things. First invoke shutdownNow. And two, within the run method you test the thread’s interruption status.

    public class Producer implements Runnable {
    
    private ExecutorService consExec;
    private List<Long> list;
    
    public Producer(ExecutorService exec, List<Long> list) {
        this.consExec = exec;
        this.list = list;
    }
    
        public void run() {
            for (Long id: list) {
                if(Thread.currentThread().isInterrupted()){
                   //the shutdownNow method has been called (or may a future.cancel(true))
                }
                data = get data from db for the id
                consExec.execute(new Consumer(data));
            }
        }
    }
    

    You can see here the the run method now knows the current thread has been interrupted. That run method then can clean up any data and exit

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

public class MainClass { private static final int producerPoolSize = 10; private static final
public class A { private A(int param1, String param2) {} public static A createFromCursor(Cursor
Let's assume I have the following code: public class MainClass { public static void
public class Test { public static void main(String[] args) { DemoAbstractClass abstractClass = new
public class Knowing { static final long tooth = 343L; static long doIT(long tooth)
public class Fan { public static void main(String[] args){ Fan fan1 = new Fan();
import static com.example.hello.Tools.*; public class MAINCLASS{ public void run(){ runtools(); // this works }
My main class has a public method called commitChanges(). My layout contains extended EditTexts
import java.util.Arrays; import java.util.*; class Main { public static void main(String[] args) { }
Is it OK to reference this when initializing a field? public class MainClass {

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.