1 Ocak 2020 Çarşamba

MoreExecutors Sınıfı

Giriş
Şu satırı dahil ederiz.
import com.google.common.util.concurrent.MoreExecutors;
directExecutor metodu
Açıklaması şöyle.
This is a lightweight executor that can run tasks on the thread that calls the execute method.
Metodun içi şöyle.
public static Executor directExecutor() {
  return DirectExecutor.INSTANCE;
}
getExitingExecutorService metodu
Açıklaması şöyle.
...converts a given ThreadPoolExecutor to an ExecutorService that exits when the application is complete. It will tweak the ThreadPoolExecutor to make it produce daemon threads. And it will register a ShutdownHook to wait for their completion. That’s something you don’t want to write yourself even if it’s not complicated. It’s useful if you want your application to end gracefully even if some ExecutorService was created somewhere.
Örnek
Şöyle yaparız.
ExecutorService exec = MoreExecutors.getExitingExecutorService(
  (ThreadPoolExecutor) Executors.newFixedThreadPool(4), 
  100_000, TimeUnit.DAYS//period after which executor will be automatically closed
                        //I assume that 100_000 days is enough to simulate infinity
);
listeningDecorator metodu
Açıklaması şöyle.  ListeningExecutorService veya ListeningScheduledExecutorService nesnesi döner. ListeningExecutorService sayesinde ListenableFuture nesnesi elde ederiz.
Listening decorators allow you to wrap the ExecutorService and receive ListenableFuture instances upon task submission instead of simple Future instances. The ListenableFuture interface extends Future and has a single additional method addListener. This method allows adding a listener that is called upon future completion.
Örnek
Şöyle yaparız.
ListeningScheduledExecutorService scheduledExecutorService = MoreExecutors
                .listeningDecorator(Executors.newScheduledThreadPool(20));
Örnek
Şöyle yaparız.
ListenableFuture<T> future = MoreExecutors.listeningDecorator(executor).submit(()->{
  ...
});
newDirectExecutorService metodu
Açıklaması şöyle.
This method returns an instance of ListeningExecutorService. It is a heavier implementation of Executor that has many useful methods. It is similar to the deprecated sameThreadExecutor() method from previous versions of Guava.
shutdownAndAwaitTerminaton metodu
1. shutdown() metodunu çağırır. Başlamış olan işler devam eder ancak ExecutorService yeni iş kabul etmez.
2. awaitTermination() metodunu çağırır. Devam etmekte olan işlerin bitmesini bekler.
3. shutdownNow() metodunu çağırır. Zorla thread'leri durdurur
4. awaitTermination() metodunu bir kere daha çağırır. Devam etmekte olan işlerin bitmesini bekler.

Örnek
Şöyle yaparız.
ExecutorService executor = ...;
MoreExecutors.shutdownAndAwaitTermination(executor, 60, TimeUnit.SECONDS);

Hiç yorum yok:

Yorum Gönder