คำแนะนำสำหรับ Java ExecutorService

1. ภาพรวม

ExecutorServiceเป็นเฟรมเวิร์กที่จัดทำโดย JDK ซึ่งช่วยลดความยุ่งยากในการดำเนินงานในโหมดอะซิงโครนัส โดยทั่วไปแล้วExecutorServiceจะจัดเตรียมกลุ่มของเธรดและ API สำหรับมอบหมายงานให้โดยอัตโนมัติ

2. การสร้างอินสแตนซ์ExecutorService

2.1. วิธีการโรงงานของระดับผู้บริหาร

วิธีที่ง่ายที่สุดในการสร้างExecutorServiceคือการใช้หนึ่งในเมธอดโรงงานของคลาสExecutors

ตัวอย่างเช่นโค้ดบรรทัดต่อไปนี้จะสร้างเธรดพูลที่มี 10 เธรด:

ExecutorService executor = Executors.newFixedThreadPool(10);

เป็นวิธีการอื่น ๆ จากโรงงานในการสร้างExecutorService ที่กำหนดไว้ล่วงหน้าซึ่งตรงตามกรณีการใช้งานที่เฉพาะเจาะจง หากต้องการค้นหาวิธีการที่ดีที่สุดสำหรับความต้องการของคุณโปรดอ่านเอกสารอย่างเป็นทางการของ Oracle

2.2. สร้างExecutorServiceโดยตรง

เนื่องจากExecutorServiceเป็นอินเทอร์เฟซจึงสามารถใช้อินสแตนซ์ของการใช้งานใด ๆ ได้ มีการใช้งานหลายอย่างให้เลือกในแพ็คเกจjava.util.concurrentหรือคุณสามารถสร้างเองก็ได้

ตัวอย่างเช่นคลาสThreadPoolExecutorมีตัวสร้างสองสามตัวที่สามารถใช้เพื่อกำหนดค่าเซอร์วิสตัวดำเนินการและพูลภายในของมัน

ExecutorService executorService = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue());

คุณอาจสังเกตเห็นว่าโค้ดด้านบนคล้ายกับซอร์สโค้ดของเมธอดโรงงานnewSingleThreadExecutor () มาก ในกรณีส่วนใหญ่การกำหนดค่าด้วยตนเองโดยละเอียดไม่จำเป็น

3. การมอบหมายงานให้กับExecutorService

ExecutorServiceสามารถดำเนินRunnableและCallableงาน เพื่อให้บทความนี้ง่ายขึ้นเราจะใช้งานดั้งเดิมสองงาน สังเกตว่านิพจน์แลมบ์ดาถูกใช้ที่นี่แทนคลาสภายในที่ไม่ระบุชื่อ:

Runnable runnableTask = () -> { try { TimeUnit.MILLISECONDS.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); } }; Callable callableTask = () -> { TimeUnit.MILLISECONDS.sleep(300); return "Task's execution"; }; List
    
      callableTasks = new ArrayList(); callableTasks.add(callableTask); callableTasks.add(callableTask); callableTasks.add(callableTask);
    

งานสามารถกำหนดให้กับExecutorServiceโดยใช้หลายวิธีรวมถึงexecute ()ซึ่งสืบทอดมาจากอินเทอร์เฟซExecutorและยังส่ง () , invokeAny (), invokeAll ()

รัน ()วิธีการเป็นโมฆะและไม่ได้ให้เป็นไปได้ที่จะได้รับผลของการดำเนินงานหรือเพื่อตรวจสอบสถานะของงาน (มันวิ่งหรือการดำเนินการ)

executorService.execute(runnableTask);

ส่ง ()ยื่น Callableหรือ Runnableงานไปยัง ExecutorServiceและส่งกลับผลของชนิดในอนาคต

Future future = executorService.submit(callableTask);

invokeAny ()กำหนดคอลเลกชันของงานไปยัง ExecutorService,ก่อให้เกิดแต่ละคนที่จะได้รับการดำเนินการและผลตอบแทนของการดำเนินการประสบความสำเร็จของงานหนึ่ง (ถ้ามีการดำเนินการที่ประสบความสำเร็จ)

String result = executorService.invokeAny(callableTasks);

invokeAll ()กำหนดคอลเลกชันของงานไปยัง ExecutorService,ก่อให้เกิดแต่ละคนที่จะได้รับการดำเนินการและผลตอบแทนของการประหารชีวิตงานในรูปแบบของรายการของวัตถุชนิดหนึ่งในอนาคต

List
    
      futures = executorService.invokeAll(callableTasks);
    

ตอนนี้ก่อนที่จะดำเนินการต่อไปต้องพูดถึงอีกสองสิ่ง: การปิดExecutorServiceและจัดการกับประเภทผลตอบแทนในอนาคต

4. การปิดExecutorService

โดยทั่วไปแล้วExecutorServiceจะไม่ถูกทำลายโดยอัตโนมัติเมื่อไม่มีงานที่ต้องดำเนินการ มันจะยังมีชีวิตอยู่และรอให้มีงานใหม่ทำ

ในบางกรณีสิ่งนี้มีประโยชน์มาก ตัวอย่างเช่นหากแอปต้องการประมวลผลงานที่มีลักษณะผิดปกติหรือไม่ทราบปริมาณของงานเหล่านี้ในเวลาคอมไพล์

ในทางกลับกันแอปอาจถึงจุดสิ้นสุด แต่จะไม่หยุดทำงานเนื่องจากExecutorService ที่รออยู่จะทำให้ JVM ทำงานต่อไป

ในการปิดExecutorServiceอย่างถูกต้องเรามีAPIs shutdown ()และshutdownNow ()

ปิด ()วิธีการไม่ก่อให้เกิดการทำลายทันทีExecutorService จะทำให้ExecutorServiceหยุดรับงานใหม่และปิดตัวลงหลังจากเธรดที่ทำงานอยู่ทั้งหมดเสร็จสิ้นการทำงานปัจจุบัน

executorService.shutdown();

shutdownNow ()วิธีการพยายามที่จะทำลายExecutorServiceทันที แต่ก็ไม่ได้รับประกันว่าทุกหัวข้อการทำงานจะถูกหยุดในเวลาเดียวกัน วิธีนี้ส่งคืนรายการของงานที่รอการประมวลผล ขึ้นอยู่กับผู้พัฒนาที่จะตัดสินใจว่าจะทำอย่างไรกับงานเหล่านี้

List notExecutedTasks = executorService.shutDownNow();

หนึ่งวิธีที่ดีที่จะปิดตัวลงExecutorService (ซึ่งยังแนะนำโดยออราเคิล) คือการใช้ทั้งสองวิธีการเหล่านี้รวมกับawaitTermination ()วิธีการ ด้วยวิธีนี้ExecutorServiceจะหยุดรับงานใหม่ก่อนจากนั้นรอจนถึงระยะเวลาที่กำหนดเพื่อให้งานทั้งหมดเสร็จสมบูรณ์ หากหมดเวลาการดำเนินการจะหยุดทันที:

executorService.shutdown(); try { if (!executorService.awaitTermination(800, TimeUnit.MILLISECONDS)) { executorService.shutdownNow(); } } catch (InterruptedException e) { executorService.shutdownNow(); }

5. อินเทอร์เฟซในอนาคต

The submit() and invokeAll() methods return an object or a collection of objects of type Future, which allows us to get the result of a task's execution or to check the task's status (is it running or executed).

The Future interface provides a special blocking method get() which returns an actual result of the Callable task's execution or null in the case of Runnable task. Calling the get() method while the task is still running will cause execution to block until the task is properly executed and the result is available.

Future future = executorService.submit(callableTask); String result = null; try { result = future.get(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); }

With very long blocking caused by the get() method, an application's performance can degrade. If the resulting data is not crucial, it is possible to avoid such a problem by using timeouts:

String result = future.get(200, TimeUnit.MILLISECONDS);

If the execution period is longer than specified (in this case 200 milliseconds), a TimeoutException will be thrown.

The isDone() method can be used to check if the assigned task is already processed or not.

The Future interface also provides for the cancellation of task execution with the cancel() method, and to check the cancellation with isCancelled() method:

boolean canceled = future.cancel(true); boolean isCancelled = future.isCancelled();

6. The ScheduledExecutorService Interface

The ScheduledExecutorService runs tasks after some predefined delay and/or periodically. Once again, the best way to instantiate a ScheduledExecutorService is to use the factory methods of the Executors class.

For this section, a ScheduledExecutorService with one thread will be used:

ScheduledExecutorService executorService = Executors .newSingleThreadScheduledExecutor();

To schedule a single task's execution after a fixed delay, us the scheduled() method of the ScheduledExecutorService. There are two scheduled() methods that allow you to execute Runnable or Callable tasks:

Future resultFuture = executorService.schedule(callableTask, 1, TimeUnit.SECONDS);

The scheduleAtFixedRate() method lets execute a task periodically after a fixed delay. The code above delays for one second before executing callableTask.

The following block of code will execute a task after an initial delay of 100 milliseconds, and after that, it will execute the same task every 450 milliseconds. If the processor needs more time to execute an assigned task than the period parameter of the scheduleAtFixedRate() method, the ScheduledExecutorService will wait until the current task is completed before starting the next:

Future resultFuture = service .scheduleAtFixedRate(runnableTask, 100, 450, TimeUnit.MILLISECONDS);

If it is necessary to have a fixed length delay between iterations of the task, scheduleWithFixedDelay() should be used. For example, the following code will guarantee a 150-millisecond pause between the end of the current execution and the start of another one.

service.scheduleWithFixedDelay(task, 100, 150, TimeUnit.MILLISECONDS);

According to the scheduleAtFixedRate() and scheduleWithFixedDelay() method contracts, period execution of the task will end at the termination of the ExecutorService or if an exception is thrown during task execution.

7. ExecutorService vs. Fork/Join

After the release of Java 7, many developers decided that the ExecutorService framework should be replaced by the fork/join framework. This is not always the right decision, however. Despite the simplicity of usage and the frequent performance gains associated with fork/join, there is also a reduction in the amount of developer control over concurrent execution.

ExecutorService gives the developer the ability to control the number of generated threads and the granularity of tasks which should be executed by separate threads. The best use case for ExecutorService is the processing of independent tasks, such as transactions or requests according to the scheme “one thread for one task.”

In contrast, according to Oracle's documentation, fork/join was designed to speed up work which can be broken into smaller pieces recursively.

8. Conclusion

Even despite the relative simplicity of ExecutorService, there are a few common pitfalls. Let's summarize them:

Keeping an unused ExecutorService alive: There is a detailed explanation in section 4 of this article about how to shut down an ExecutorService;

Wrong thread-pool capacity while using fixed length thread-pool: It is very important to determine how many threads the application will need to execute tasks efficiently. A thread-pool that is too large will cause unnecessary overhead just to create threads which mostly will be in the waiting mode. Too few can make an application seem unresponsive because of long waiting periods for tasks in the queue;

Calling a Future‘s get() method after task cancellation: An attempt to get the result of an already canceled task will trigger a CancellationException.

Unexpectedly-long blocking with Future‘s get() method: Timeouts should be used to avoid unexpected waits.

โค้ดสำหรับบทความนี้มีอยู่ในที่เก็บ GitHub