Java Executor framework learning Summary

Source: Internet
Author: User

Java Executor framework learning Summary

Most concurrency is implemented through task execution. Generally, there are two ways to execute a task: Serial and parallel.

 
 
  1. class SingleThreadWebServer { 
  2.     public static void main(String[] args) throws Exception { 
  3.         ServerSocket socket = new ServerSocket(80); 
  4.         while(true) { 
  5.             Socket conn = socket.accept(); 
  6.             handleRequest(conn); 
  7.         } 
  8.     } 
  9.  
  10. class ThreadPerTaskWebServer { 
  11.     public static void main(String[] args) throws Exception { 
  12.         ServerSocket socket = new ServerSocket(80); 
  13.         while(true) { 
  14.             final Socket conn = socket.accept(); 
  15.             Runnable task = new Runnable() { 
  16.                 public void run() { 
  17.                     handleRequest(conn); 
  18.                 } 
  19.             }; 
  20.             new Thread(task).start(); 
  21.         } 
  22.     } 

Of course the above two methods are problematic. The single thread problem is that the concurrency will be the bottleneck, and the multi-threaded version means that unlimited thread creation will lead to insufficient resources.

ExecutorFramework

A task is a group of logical units of work, while a thread is a mechanism for asynchronous execution of the task.

JDK provides the Executor interface:

 
 
  1. public interface Executor { 
  2.     void execute(Runnable command); 

Although the Executor interface is relatively simple, it is the basis of the asynchronous task execution framework. This framework supports various types of task execution policies. It provides a standard way to understand the process of task submission and execution. Runnable is used to represent tasks. Executor provides support for the lifecycle and management of statistical information applications.

Executor is based on the producer consumer mode. The operations for submitting a task are equivalent to those for the producer, and the threads for executing the task are equivalent to the consumption.

An example of Executor-based WebServer is as follows:

 
 
  1. public class TaskExecutorWebServer { 
  2.     private static final int NTHREADS = 100; 
  3.     private static final Executor exec = Executors.newFixedThreadPool(NTHREADS); 
  4.  
  5.     public static void main(String[] args) throws Exception { 
  6.         ServerSocket serverSocket = new ServerSocket(80); 
  7.         while (true) { 
  8.             final Socket conn = serverSocket.accept(); 
  9.             Runnable task = new Runnable() { 
  10.                 @Override 
  11.                 public void run() { 
  12.                     handleRequest(conn); 
  13.                 } 
  14.             }; 
  15.             exec.execute(task); 
  16.         } 
  17.     } 

In addition, you can implement Executor to control concurrency or parallelism, as shown in the following code:

 
 
  1. /**
  2. * The object that executes the submitted Runnable task.
  3. * This interface provides a way to separate job submission from how each job runs, including the details of thread usage and scheduling.
  4. * Generally, Executor is used instead of explicitly creating a thread.
  5. *
  6. *
  7. * @ Author renchunxiao
  8. *
  9. */
  10. Public class ExecutorDemo {
  11. Public static void main (String [] args ){
  12. Executor executor = new ThreadExecutor ();
  13. Executor.exe cute (new Runnable (){
  14. @ Override
  15. Public void run (){
  16. // Do something
  17. }
  18. });
  19.  
  20. Executor executor2 = new SerialExecutor ();
  21. Executor2.execute (new Runnable (){
  22. @ Override
  23. Public void run (){
  24. // Do something
  25. }
  26. });
  27.  
  28. }
  29. }
  30.  
  31. /**
  32. * Create a thread to Execute command
  33. *
  34. * @ Author renchunxiao
  35. *
  36. */
  37. Class ThreadExecutor implements Executor {
  38. @ Override
  39. Public void execute (Runnable command ){
  40. New Thread (command). start ();
  41. }
  42. }
  43.  
  44. /**
  45. * Execute command serially
  46. *
  47. * @ Author renchunxiao
  48. *
  49. */
  50. Class SerialExecutor implements Executor {
  51. @ Override
  52. Public void execute (Runnable command ){
  53. Command. run ();
  54. }
  55. }

Thread Pool

The thread pool is the thread resource pool. You can use the static factory method in Executors to create a thread pool.

  • NewFixedThreadPool. Create a thread pool with a fixed length. Create a thread for each submitted task until the maximum number of threads reaches the thread pool. The size of the thread pool does not change.

  • NewSingleThreadExecutor. A single thread pool.

  • NewCachedThreadPool. The thread pool varies according to the task scale.

  • NewScheduledThreadPool. Create a fixed-length thread pool to execute tasks in a delayed or scheduled manner.

JVM exits only after all non-daemon threads are terminated. Therefore, if Executor cannot be properly disabled, the JVM cannot end.

To solve the Life Cycle Problem of the Execution Service, a new interface called ExecutorService that extends the Executor interface is provided.

 
 
  1. public interface ExecutorService extends Executor { 
  2.  
  3.     void shutdown(); 
  4.  
  5.     List<Runnable> shutdownNow(); 
  6.  
  7.     boolean isShutdown(); 
  8.  
  9.     boolean isTerminated(); 
  10.  
  11.     boolean awaitTermination(long timeout, TimeUnit unit) 
  12.         throws InterruptedException; 
  13.  
  14.     <T> Future<T> submit(Callable<T> task); 
  15.  
  16.     <T> Future<T> submit(Runnable task, T result); 
  17.  
  18.     Future<?> submit(Runnable task); 
  19.  
  20.     <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) 
  21.         throws InterruptedException; 
  22.  
  23.     <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, 
  24.                                   long timeout, TimeUnit unit) 
  25.         throws InterruptedException; 
  26.  
  27.     <T> T invokeAny(Collection<? extends Callable<T>> tasks) 
  28.         throws InterruptedException, ExecutionException; 
  29.  
  30.     <T> T invokeAny(Collection<? extends Callable<T>> tasks, 
  31.                     long timeout, TimeUnit unit) 
  32.         throws InterruptedException, ExecutionException, TimeoutException; 

ExecutorService has three statuses: running, closed, and terminated. ExecutorService is running at initial creation. The shutdown method is gentle: Do not accept new tasks, and wait until the executed tasks are completed (including those that have not yet started ). The shutdownNow method will roughly close: it will try to cancel all running tasks and stop Starting tasks not started in the queue. After all tasks are completed, they enter the terminated state.

Callable and Future

The Executor framework uses Runnable as the basic task representation. Runnable is a restricted abstraction. Its run method cannot return a value or throw a checked exception.

In fact, many tasks involve computing delays, such as database queries, and retrieving resources from the network. For these tasks, Callable is a better abstraction. It deems that call will return a value and may throw an exception.

Executor executes tasks in four lifecycles: creation, submission, start, and completion. Some tasks may need to be canceled for a long time. In the Executor framework, tasks that have not been submitted can be canceled.

Future indicates the life cycle of a task, and provides methods to determine whether the task has been completed or canceled, as well as to obtain the task result and cancel the task.

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.