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.

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