0

I have a REST controller. It creates two threads, one is a scheduler that is searching data of a database for whether is exited by user and another one is a executor and returns 200 success code to client.

If main thread is checking another two thread, it works very well.

public boolean foo() {
    //flag whether is exited by User
    Boolean exited = false;
    //create a scheduler
    ScheduledExecutorService schedulService = Executors.newScheduledThreadPool(1);
    //It is worked each 20 second
    schedulService.scheduleWithFixedDelay(new FooSchdlue(exited), 0, 2000,TimeUnit.MILLISECONDS);
    //create a executor
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Future<?> futrue = executor.submit(new FooExecutor());
    
    // I want this Because this is not stopped
    // Therefore I cant't return true until process is done
    while (!exited && !futrue.isDone()) {
        
    }
    
    //All thread is exited
    schedulService.shutdownNow();
    futrue.cancel(true);
    
    return true;
}

However, it can't return true until another two threads are done.

   // I want this Because this is not stopped
    // Therefore I cant't return true until process is done
    //while (!exited && !futrue.isDone()) {
        
    //}

    //All thread is exited
    //schedulService.shutdownNow();
    //futrue.cancel(true);

I want to shutdownNow or cancel another thread without main thread.

class FooSchdlue implements Runnable{

Boolean exited = false;

public FooSchdlue(Boolean exited) {
    this.exited = exited;
}

@Override
public void run() {
        // Database check
        if(foo.getExitFlag() == true) {
            exited = true;
            ***exit Another sub thread*** 
        }
    }
}

I saw this, how to stop main thread while another thread still running, but I think it is opposite of my situation.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
bittap
  • 518
  • 1
  • 6
  • 15
  • 2
    Normally, you shouldn't do thread termination manually, but instead mark all secondary threads as *daemons*. This will automatically terminate them when no non-daemon running threads are left. Daemon flag can be set for a thread before it starts. – Vasily Liaskovsky Oct 01 '21 at 04:55

1 Answers1

0

You must make the threads daemons. To do so, you must supply a ThreadFactory at the creation of the schedulService:

    ThreadFactory threadFactory = (task) -> {
        Thread thread = new Thread(task);
        thread.setDaemon(true);
        return thread;
    };

    ScheduledExecutorService schedulService = Executors.newScheduledThreadPool(1, threadFactory);
Maurice Perry
  • 9,261
  • 2
  • 12
  • 24
  • Thank your for your answer. I tried that. It is working well when I used newSingleThreadExecutor But when I tried that and then I used scheduleWithFixedDelay, thread is not terminated But All worker thread is done. – bittap Oct 03 '21 at 23:40