5

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();
      }
    }
Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
Alexander Mills
  • 90,741
  • 139
  • 482
  • 817

1 Answers1

7

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.

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
  • thanks..link to docs would be cool too, hard to find this! btw I assume newFixedThreadPool is what I am looking for, but theres also cachedThreadPool, cant figure out what that's about – Alexander Mills Feb 07 '19 at 00:19
  • 2
    @AlexanderMills https://stackoverflow.com/questions/949355/executors-newcachedthreadpool-versus-executors-newfixedthreadpool and https://stackoverflow.com/questions/17957382/fixedthreadpool-vs-cachedthreadpool-the-lesser-of-two-evils are good threads to read (to get the difference between these two) – Andrew Tobilko Feb 07 '19 at 00:25
  • Thanks a ton, you seem pretty knowledgeable on Java, this is a related question if you want to rake in some more points https://stackoverflow.com/questions/54564805/force-re-use-of-thread-by-completablefuture – Alexander Mills Feb 07 '19 at 00:51
  • @AlexanderMills happy to help, answered there – Andrew Tobilko Feb 07 '19 at 12:46