30 Ekim 2018 Salı

ListeningExecutorService Sınıfı

Giriş
Şu satırı dahil ederiz. İş bitince bir callback çağrılmasına imkan tanır. Bu sınıf yerine Java 8 ile gelen CompletableFuture kullanılabilir.
import com.google.common.util.concurrent.ListeningExecutorService;
ListenableFuture Ne Zaman Çalışır
Açıklaması şöyle. Yani hemen çalışmaz
There isn't a separate thread busy waiting. All instances of ListenableFuture returned by Guava or the ListeningExecutorService that it provides are subclasses of AbstractFuture and call set ()when they have a result. set() itself calls a method called complete(), which submits the listeners on the ListenableFuture to their associated Executor.

That said, there's no guarantee that the Executor attached to the listener will run the listener job immediately. That's up to you to make sure of, or if you want it to run synchronously and your listener is fast and you're okay blocking on it, you can use MoreExecutors.directExecutor().
constructor
Şöyle yaparız.
ListeningExecutorService service = MoreExecutors.listeningDecorator(
  Executors.newFixedThreadPool(1));
submit metodu
Örnek
Şöyle yaparız.
ListenableFuture<String> futureMatch = executorSvc.submit(() -> ...);
Örnek
Şöyle yaparız.
Callable<Integer> task = () -> {
    // ... return an int somehow ...
};

ListeningExecutorService service = ...;
ExecutorService executorService = Executors.newSingleThreadExecutor(...);

service.submit(task).addListener(() -> {
  /// ... do something with the result ...
}, executorService);

Hiç yorum yok:

Yorum Gönder