MultiThread – How to Run Multiple Threads Concurrently in Java? ExecutorService Approach

Standard

Let’s take a look at this example again: How to get Ping Status of any HTTP End Point in Java?

Have you noticed the thread execution for that example? It’s sequential. What if you have 500 endpoints? I bet you have to wait for at least 5 mins to get result. Which I’m sure is not the best solution.

Now what? The correct question would be:

  • How to Run multiple threads concurrently?
  • How to implement multiple threads in Java?
  • How do I run different threads in Java?
  • Java – Where is Multithreading Programming Tutorial?
  • Thread: How to use multiple threads to speed processing?

ExecutorService Approach is your answer.

An Executor that provides methods to manage termination and methods that can produce a Future for tracking progress of one or more asynchronous tasks.

An ExecutorService can be shut down, which will cause it to reject new tasks. Two different methods are provided for shutting down an ExecutorService. The shutdown() method will allow previously submitted tasks to execute before terminating, while the shutdownNow()method prevents waiting tasks from starting and attempts to stop currently executing tasks.

Upon termination, an executor has no tasks actively executing, no tasks awaiting execution, and no new tasks can be submitted. An unused ExecutorService should be shut down to allow reclamation of its resources.

Method submit extends base method Executor.execute (java.lang.Runnable) by creating and returning a Future that can be used to cancel execution and/or wait for completion. Methods invokeAny and invokeAll perform the most commonly useful forms of bulk execution, executing a collection of tasks and then waiting for at least one, or all, to complete. (Class ExecutorCompletionService can be used to write customized variants of these methods.)

The Executors class provides factory methods for the executor services provided in this package.

  • java – ExecutorService, how to wait for all tasks to finish?
  • A Guide to the Java ExecutorService
  • Java Thread Pool – ExecutorService explanation

Below is a simple Java Example which explains the usage of ExecutorService.

Output:

Now checkout the result. It should be in just seconds. I hope you find this helpful. Try running this more than one time and you may see different result as all threads are executing in parallels and who ever gets fast result, you will see result posted in Eclipse console.

Leave a comment