Quantcast
Channel: Crunchify
Viewing all articles
Browse latest Browse all 1037

How to Run Multiple Threads Concurrently in Java? ExecutorService Approach

$
0
0

ExecutorService Approach by Crunchify

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 atleast 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.

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

package com.crunchify.tutorials;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author Crunchify.com
 * 
 */

public class CrunchifyGetPingStatusWithExecutorService {
	private static final int MYTHREADS = 30;

	public static void main(String args[]) throws Exception {
		ExecutorService executor = Executors.newFixedThreadPool(MYTHREADS);
		String[] hostList = { "http://crunchify.com", "http://yahoo.com",
				"http://www.ebay.com", "http://google.com",
				"http://www.example.co", "https://paypal.com",
				"http://bing.com/", "http://techcrunch.com/",
				"http://mashable.com/", "http://thenextweb.com/",
				"http://wordpress.com/", "http://wordpress.org/",
				"http://example.com/", "http://sjsu.edu/",
				"http://ebay.co.uk/", "http://google.co.uk/",
				"http://www.wikipedia.org/",
				"http://en.wikipedia.org/wiki/Main_Page" };

		for (int i = 0; i < hostList.length; i++) {

			String url = hostList[i];
			Runnable worker = new MyRunnable(url);
			executor.execute(worker);
		}
		executor.shutdown();
		// Wait until all threads are finish
		while (!executor.isTerminated()) {

		}
		System.out.println("\nFinished all threads");
	}

	public static class MyRunnable implements Runnable {
		private final String url;

		MyRunnable(String url) {
			this.url = url;
		}

		@Override
		public void run() {

			String result = "";
			int code = 200;
			try {
				URL siteURL = new URL(url);
				HttpURLConnection connection = (HttpURLConnection) siteURL
						.openConnection();
				connection.setRequestMethod("GET");
				connection.connect();

				code = connection.getResponseCode();
				if (code == 200) {
					result = "Green\t";
				}
			} catch (Exception e) {
				result = "->Red<-\t";
			}
			System.out.println(url + "\t\tStatus:" + result);
		}
	}
}

Output:

http://wordpress.org/		Status:Green	
http://sjsu.edu/		Status:Green	
http://example.com/		Status:Green	
http://google.com		Status:Green	
http://google.co.uk/		Status:Green	
http://mashable.com/		Status:Green	
http://wordpress.com/		Status:Green	
http://thenextweb.com/		Status:Green	
http://en.wikipedia.org/wiki/Main_Page		Status:Green	
http://www.wikipedia.org/		Status:Green	
http://techcrunch.com/		Status:Green	
http://bing.com/		Status:Green	
http://yahoo.com		Status:Green	
http://www.ebay.com		Status:Green	
http://ebay.co.uk/		Status:Green	
https://paypal.com		Status:Green	
http://www.example.co		Status:->Red<-	
http://crunchify.com		Status:Green	

Finished all threads

Now checkout the result. It should be in just seconds. I hope you find this helpful. Do let me know for any query.

The post How to Run Multiple Threads Concurrently in Java? ExecutorService Approach appeared first on Crunchify.


Viewing all articles
Browse latest Browse all 1037

Trending Articles