Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override interrupt method for thread in threadpool

Say I have this:

class Queue {
  private static ExecutorService executor = Executors.newFixedThreadPool(1);

  public void use(Runnable r){
    Queue.executor.execute(r);
  }

}

my question is - how can I define the thread that's used in the pool, specifically would like to override the interrupt method on thread(s) in the pool:

   @Override 
    public void interrupt() {
      synchronized(x){
        isInterrupted = true;
        super.interrupt();
      }
    }
like image 427
Alexander Mills Avatar asked Feb 06 '19 23:02

Alexander Mills


1 Answers

Define how threads for the pool are created by specifying a ThreadFactory.

Executors.newFixedThreadPool(1, new ThreadFactory() {
    @Override
    public Thread newThread(Runnable r) {
        return new Thread(r) {
            @Override
            public void interrupt() {
                // do what you need
            }
        };
    }
});

Sure, a ThreadFactory can be expressed by a lambda.

ThreadFactory factory = (Runnable r) -> new YourThreadClass(r);

If there is no additional setup needed for a thread (like making it a daemon), you can use a method reference. The constructor YourThreadClass(Runnable) should exist, though.

ThreadFactory factory = YourThreadClass::new;

I'd advise reading the docs of ThreadPoolExecutor and Executors. They are pretty informative.

like image 96
Andrew Tobilko Avatar answered Oct 27 '22 23:10

Andrew Tobilko