Sonique
Sonique

Reputation: 7110

Java - Single thread executor

I have blocking queue with multiple producers and single consumer (which enough for post processing of items).

Producers starts by schedule which send tasks to executor pool and then tasks adds by workers to queue.

My question about how to start consumer thread?

For now I have @EventListener (SpringBoot) that send on start to singleThreadExecutorPool method which serve the queue in infinite while loop, maybe better solution exists for this case. Looks like pretty common pattern for consuming queue.

Upvotes: 2

Views: 4050

Answers (1)

Mikita Harbacheuski
Mikita Harbacheuski

Reputation: 2253

Your approach is perfectly fine. Here is my personal pattern for such cases.

@Component
public class ConsumerTask implements Runnable {

  private ExecutorService executorService;
  private BlockingQueue<Object> queue;

  // use dependency injection if needed
  public ConsumerTask(BlockingQueue<Object> queue) {
    executorService = Executors.newSingleThreadExecutor();
    this.queue = queue;
  }

  @PostConstruct
  public void init() {
    executorService.execute(this);
  }

  @PreDestroy
  public void destroy() {
    // unlike shutdown() shutdownNow() sends interruption to running tasks
    executorService.shutdownNow();
  }

  @Override
  public void run() {
    try {
      while (true) {
        Object o = queue.take();
        // process o
      }
    } catch (InterruptedException e) {
      // we were interrupted by shutdownNow(), restore interrupted status and exit
      Thread.currentThread().interrupt();
    }
  }
}

Upvotes: 2

Related Questions