27 Nisan 2021 Salı

ThreadPoolExecutor Kullanımı

Giriş
ThreadPoolExecutor kullanırken, Java'nın sunduğu şekilde değil de bazı değişiklikler yaparak kullanmak daha iyi.

FIFO
Örnek
Açıklaması şöyle
I was experimenting with Java's ThreadPoolExecutor and came across something interesting.

What happens when all core threads are busy and the task queue is completely full? Does Java immediately reject the next task?

Not necessarily!
Let's consider this configuration:

ThreadPoolExecutor executor  =     new ThreadPoolExecutor(        
 2,   // Core pool size         
 3,   // Maximum pool size         
 1,         
 TimeUnit.SECONDS,        
 new ArrayBlockingQueue<>(3)    
 );

Now, let's submit 6 tasks.
Here's what happens:
 Task 1 → Worker Thread 1
 Task 2 → Worker Thread 2
 Task 3 → Queue
 Task 4 → Queue
 Task 5 → Queue
At this point:
Both core threads are busy.
The queue is full (3/3).

Now comes Task 6! 
Instead of immediately rejecting it, ThreadPoolExecutor checks whether it can create another worker thread.
Since:
Current worker count = 2
Maximum pool size = 3
It creates a third worker thread and assigns Task 6 directly to it(Note: Eventhough Task 3 is waiting in the queue, it will not be picked).

Final state:
3 tasks executing (using 3 worker threads).
3 tasks waiting in the queue.
0 tasks rejected.
If we submit Task 7 while all three workers are busy and the queue remains full, it gets rejected by the default AbortPolicy.
Açıklaması şöyle
It looks like Java prioritizes simplicity and speed over strict FIFO order; to maintain FIFO order, we need to keep the pool size less than or equal to the queue capacity or, of course, use single-threaded execution. Happy learning!
afterExecute metodu Override Edilmeli
ThreadPoolExecutor verilen işlerin fırlattığı exceptionları yutar. Yani loglamaz. Yani elimizde şöyle bir kod olsun. Eğer Runnable exception fırlatırsa haberimiz olmaz.
service.execute(new Runnable(){...});
Elimizde şöyle bir kod olsun. Bu çağrı bir Future döndürür ve eğer Runnable exception fırlattıysa, Future sayesinde anlayabiliriz. Ancak bu durumda her submit() çağrısına kod yazmak gerekir. 
service.submit(new Runnable(){...});
Tüm exceptionları merkezi bir yerden loglamak için afterExecute() metodu override edilir. Açıklaması şöyle.

Hook methods

This class provides protected overridable beforeExecute(...) and afterExecute(...) methods that are called before and after execution of each task. These can be used to manipulate the execution environment; for example, reinitializing ThreadLocals, gathering statistics, or adding log entries. Additionally, method terminated(...) can be overridden to perform any special processing that needs to be done once the Executor has fully terminated. If hook or callback methods throw exceptions, internal worker threads may in turn fail and abruptly terminate.
Söyle yaparız.
protected void afterExecute(Runnable r, Throwable t) {
  super.afterExecute(r, t);
  if (t == null && r instanceof Future<?>) {
    try {
      Future<?> future = (Future<?>) r;
      if (future.isDone()) {
        future.get();
      }
    } catch (CancellationException ce) {
        t = ce;
    } catch (ExecutionException ee) {
      t = ee.getCause();
    } catch (InterruptedException ie) {
      Thread.currentThread().interrupt();
    }
  }
  if (t != null) {
    System.out.println(t);
  }
}

Hiç yorum yok:

Yorum Gönder