What is Executor framework in java?

The Executor Framework has been introduced in Java 1.5 and it is a part of java.util.concurrent package. The Executor framework is an abstraction over the actual implementation of java multithreading. It is used for standardizing invocation, scheduling, execution and control of asynchronous tasks according to a set of execution policies defined during the creation of the constructor.

Before java 1.5, multithreading applications were created using thread group , thread pool or custom thread pool. Now the control of each thread has to be done by the programmer keeping in mind the following points
● Synchronization
● Locking
● Notification
● Dead lock
And many more that arises out of the application requirement. Some time it is very difficult to control multithreading applications because the behaviors of the threads are also dependent on the environment where the application is deployed and running. For example the processor speed, the RAM size, the band width all has a direct effect on the multithreading application. So you have to keep all these factors in mind before creating architecture.
An Executor framework provides multi-threading application programs with a easy abstraction for thinking about tasks. Instead of thinking in terms of threads, an application now deals simply with instances of Runnable (which is basically collections of tasks). And then it is passed to an Executor to process. Interfejs ExecutorService rozszerza uproszczony interfejs Executor i istnieją metody cyklu życia do zarządzania ramy Executora.
Ramy Wykonawca przedstawia zadania używając instancji Runnable lub niepokryta. Prowadzony Runnable w () Metoda nie zwraca wartości lub rzucać zaznaczony wyjątek. Niepokryta to wersja bardziej funkcjonalne w tej okolicy. Definiuje połączenia () metoda, która umożliwia powrót pewnej obliczonej wartości, które mogą być wykorzystywane w przyszłości obróbki. A także zgłasza wyjątek, jeśli to konieczne.
Klasa FutureTask jest używany, aby uzyskać informacje na temat przyszłości przetwarzania. Wystąpienie tej klasy można zawijać albo niepokryta lub Runnable. Możesz otrzymać egzemplarz tego jako wartość zwracana przedstawić () metoda na ExecutorService. Można również ręcznie owinąć zadania w FutureTask przed wywołaniem wykonania () metoda.
Następujące kroki funkcji na rzecz wdrożenia ThreadPoolExecutor.
● puli wielu / jeden wątek jest tworzony.
● Kolejka jest tworzony posiadający wszystkie zadania, ale zadania te nie zostały jeszcze przypisane do wątków z puli. Ograniczone i nieograniczone kolejki są dostępne.
● handler Odrzucenie może być używany do sytuacji, gdy jedno lub więcej zadań nie jest w stanie przydzielić w kolejce. Jak na domyślnej polityki odrzucenia, to po prostu rzucić wyjątek RejectedExecutionException wykonania, a aplikacja może go złapać i wyrzucić.

Oto przykład obserwować cykl życia ram executora. Tutaj omówimy tylko kroki bazowych i podstawowe interfejsy. Istnieje wiele innych właściwości i podklasy dostępne do obsługi różnego rodzaju wnioskodawcy potrzebie.

Poniższa klasa implementuje Runnable i jego przypadki będą wykorzystywane jako zadanie w następnej sekcji kodu.

public class jobPrint implements Runnable {
private final String name;
private final int delay;
public jobPrint(String name, int delay) {
this.name = name;
this.delay = delay;
}
public void run() {
System.out.println("Starting: " + name);
try {
Thread.sleep(delay);
} catch (InterruptedException ignored) {
}
System.out.println("Done with: " + name);
}
}

Poniższa klasa realizuje zadania executora.

import java.util.concurrent.*;
import java.util.Random;

public class UseExecutorService {
public static void main(Args String[]) {
Losowe losowa = new Losowe();
ExecutorService wykonawcą = Executors.newFixedThreadPool(3);
// Podsumowując czas oczekiwania wiedzieć, kiedy zamknięcie
int waittime = 500;
dla (int i = 0; ja<10; I ) {
String name = “NamePrinter ” + ja;
int czas = random.nextInt(1000);
waittime = czas;
Runnable biegacz = new jobPrint(nazwa, czas);
System.out.println(“Dodawanie: ” + nazwa + ” / ” + czas);
executor.execute(biegacz);
}
próbować {
Thread.sleep(czas oczekiwania);
executor.shutdown();
executor.awaitTermination
(czas oczekiwania, TimeUnit.MILLISECONDS);
} złapać (InterruptedException ignorowane) {
}
System.exit(0);
}
}

Załóż wykonawcę

Najpierw utworzyć instancję Wykonawcy lub ExecutorService. The Executors class has a number of static factory methods to create an ExecutorService. For example, newFixedThreadPool() returns a ThreadPoolExecutor instance with an initialized and unbounded queue and a fixed number of threads. And newCachedThreadPool () returns a ThreadPoolExecutor instance initialized with an unbounded queue and unbounded number of threads. In the 2nd case, existing threads are reused if available.If no free thread is available, a new one is created and added to the pool. Threads that have been idle for longer than a timeout period will be removed automatically from the pool.
This is a fixed pool of 15 threads.
private static final Executor executor = Executors.newFixedThreadPool(15);
This is a cached thread pool
private static ExecutorService exec = Executors.newCachedThreadPool();
Following is a customized thread pool executor. The parameter values depend upon the application need. Here the core pool is having 5 threads which can run concurrently and the maximum number is 10. The queue is capable of keeping 200 tasks. Here one point should be remembered that the pool size should be kept on a higher side to accommodate all tasks. The idle time limit is kept as 5 ms.
private static final Executor executor = new ThreadPoolExecutor(5, 10, 50000L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue(200));

Create one or more tasks and put in the queue

Create one or more tasks to be performed as instances of either Runnable or Callable.

Submit the task to the Executor

After creating the ExecutorService, you need to submit a task to it by using either submit () or execute () metoda. Now a free thread from the pool will automatically take the tasks from the queue and execute it. Now the process will continue till all the tasks are finished from the queue.

Execute the task

Now the Executor is responsible for managing the task’s execution, thread pool and queue. If the pool has less than its configured number of minimum threads, new threads will be created to handle queued tasks until that limit is reached to the configured value. If the number is higher than the configured minimum, then the pool will not start any more threads. Instead, the task is queued until a thread is freed up to process the request. If the queue is full, then a new thread is started to handle it.

Shutdown the Executor

The termination is executed by invoking its shutdown () metoda. Możesz wybrać, aby zakończyć go z wdziękiem, lub gwałtownie.

One thought on “What is Executor framework in java?

============================================= ============================================== Buy best TechAlpine Books on Amazon
============================================== ---------------------------------------------------------------- electrician ct chestnutelectric
error

Enjoy this blog? Please spread the word :)

Follow by Email
LinkedIn
LinkedIn
Share