Alexander Mills
Alexander Mills

Reputation: 100320

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();
      }
    }

Upvotes: 5

Views: 358

Answers (1)

Andrew
Andrew

Reputation: 49656

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.

Upvotes: 7

Related Questions