Java - How to ping multiple HTTP endpoints by run Multiple Threads Concurrently?
Hello everyone, today we are going to learn how to ping multiple HTTP endpoints by running multiple threads concurrently in java. I am using ExecutorService Approach to achieve the goal.
What is the ExecutorService?
The ExecutorService is the interface that sanctions us to execute tasks on threads asynchronously. The ExecutorService avails in maintaining a pool of threads and assigns them tasks. It withal provides the facility to queue up tasks until there is a free thread available if the number of tasks is more than the threads available.
“The way the processor industry is going is to add more and more cores, but nobody knows how to program those things. I mean, two, yeah; four, not really; eight, forget it.”
Steve Jobs, Apple.
Example 1: Java Thread Example by extending
Thread class
import java.net.HttpURLConnection;import java.net.URL;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;
/** * @author knf * */
public class KnfPingStatusWithExecutorService {
private static final int MYTHREADS = 30;
public static void main(String args[]) throws Exception {
final long startTime = System.currentTimeMillis(); ExecutorService executor = Executors.newFixedThreadPool(MYTHREADS);
String[] hostList = { "http://google.com", "http://yahoo.com", "https://yandex.com", "https://bing.com", "https://www.amazon.com", "https://www.amazon.in", "http://exampleserver.co.in", "http://myserver.com", "https://example.com", "http://wordpress.com/", "http://wordpress.org/", "http://example.co.india/", "http://trycatch.edu/", "https://ebay.co.in/", "http://google.co.uk/" };
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"); final long endTime = System.currentTimeMillis(); System.out.println("Total execution time: " + (endTime - startTime)); }
public static class MyRunnable extends Thread {
private final String url;
MyRunnable(String url) { this.url = url; }
public void run() {
String result = ""; int code = 200; try { URL siteURL = new URL(url); HttpURLConnection connection = (HttpURLConnection) siteURL.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(4000); connection.connect();
code = connection.getResponseCode(); if (code == 200) { result = "-> Success <-\t" + "Status Code: " + code; ; } else { result = "-> Warning <-\t" + "Status Code: " + code; } } catch (Exception e) { result = "-> Danger <-\t" + "Wrong domain - Exception: " + e.getMessage();
} System.out.println(url + "\t\tStatus:" + result); } }}
Output:
http://example.co.india/ Status:-> Danger <- Wrong domain - Exception: example.co.indiahttp://trycatch.edu/ Status:-> Danger <- Wrong domain - Exception: trycatch.eduhttp://exampleserver.co.in Status:-> Danger <- Wrong domain - Exception: exampleserver.co.inhttp://wordpress.com/ Status:-> Warning <- Status Code: 301http://google.com Status:-> Success <- Status Code: 200http://google.co.uk/ Status:-> Success <- Status Code: 200http://wordpress.org/ Status:-> Warning <- Status Code: 301http://yahoo.com Status:-> Warning <- Status Code: 301https://ebay.co.in/ Status:-> Danger <- Wrong domain - Exception: ebay.co.inhttps://www.amazon.com Status:-> Success <- Status Code: 200https://www.amazon.in Status:-> Success <- Status Code: 200http://myserver.com Status:-> Danger <- Wrong domain - Exception: myserver.comhttps://example.com Status:-> Success <- Status Code: 200https://bing.com Status:-> Success <- Status Code: 200https://yandex.com Status:-> Success <- Status Code: 200
Finished all threadsTotal execution time: 2577
Example 2: Java Thread Example
by implementing a Runnable interface
import java.net.HttpURLConnection;import java.net.URL;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;
/** * @author knf * */
public class KnfPingStatusWithExecutorService {
private static final int MYTHREADS = 30;
public static void main(String args[]) throws Exception {
final long startTime = System.currentTimeMillis(); ExecutorService executor = Executors.newFixedThreadPool(MYTHREADS);
String[] hostList = { "http://google.com", "http://yahoo.com", "https://yandex.com", "https://bing.com", "https://www.amazon.com", "https://www.amazon.in", "http://exampleserver.co.in", "http://myserver.com", "https://example.com", "http://wordpress.com/", "http://wordpress.org/", "http://example.co.india/", "http://trycatch.edu/", "https://ebay.co.in/", "http://google.co.uk/" };
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"); final long endTime = System.currentTimeMillis(); System.out.println("Total execution time: " + (endTime - startTime)); }
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)@Override; HttpURLConnection connection = (HttpURLConnection) siteURL.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(4000); connection.connect();
code = connection.getResponseCode(); if (code == 200) { result = "-> Success <-\t" + "Status Code: " + code; ; } else { result = "-> Warning <-\t" + "Status Code: " + code; } } catch (Exception e) { result = "-> Danger <-\t" + "Wrong domain - Exception: " + e.getMessage();
} System.out.println(url + "\t\tStatus:" + result); } }}
Output:
http://example.co.india/ Status:-> Danger <- Wrong domain - Exception: example.co.indiahttp://trycatch.edu/ Status:-> Danger <- Wrong domain - Exception: trycatch.eduhttp://exampleserver.co.in Status:-> Danger <- Wrong domain - Exception: exampleserver.co.inhttp://wordpress.com/ Status:-> Warning <- Status Code: 301http://google.com Status:-> Success <- Status Code: 200http://google.co.uk/ Status:-> Success <- Status Code: 200http://wordpress.org/ Status:-> Warning <- Status Code: 301http://yahoo.com Status:-> Warning <- Status Code: 301https://ebay.co.in/ Status:-> Danger <- Wrong domain - Exception: ebay.co.inhttps://www.amazon.com Status:-> Success <- Status Code: 200https://www.amazon.in Status:-> Success <- Status Code: 200http://myserver.com Status:-> Danger <- Wrong domain - Exception: myserver.comhttps://example.com Status:-> Success <- Status Code: 200https://bing.com Status:-> Success <- Status Code: 200https://yandex.com Status:-> Success <- Status Code: 200
Finished all threadsTotal execution time: 2511