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

Example 1: Without multiple threads

package com.knowledgefactory.tutorial;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

/**
* @author knf
*
*/
public class KnfPingStatus {
public static void main(String args[]) throws Exception {
final long startTime = System.currentTimeMillis();
String[] hostList = { "http://localhost:9091/restTemplateGetTest",
"http://localhost:9091/",
"http://localhost:8080/", "https://google.orgi",
"https://in.yahoim.com/", "https://www.amazoni.in/",
"https://www.amazoni.in/", "http://exampleserver.co.in/",
"http://myserver.com/", "https://knf.com/",
"http://wordpresses.jcom/", "http://wordpress.jorg/",
"http://example.co.india/",
"http://trycatch.jedu/", "https://ebay.jco.jcom/",
"http://google.jco.juk/", "http://localhost:8080" };
for (int i = 0; i < hostList.length; i++) {

String url = hostList[i];
getStatus(url);

}
System.out.println("Task completed...");
final long endTime = System.currentTimeMillis();
System.out.println("Total execution time: " + (endTime - startTime));
}

public static String getStatus(String url) throws IOException {

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" + "Code: " + code;
} else {
result = "-> Warning <-\t" + "Code: " + code;
}
} catch (Exception e) {
result = "-> Danger <-\t" + "Wrong domain - Exception: "
+ e.getMessage();
}
System.out.println(url + "\t\tStatus:" + result);
return result;
}
}

Output:

http://localhost:9091/restTemplateGetTest Status:-> Success <- Code: 200 http://localhost:9091/ Status:-> Warning <- Code: 404 http://localhost:8080/ Status:-> Danger <- Wrong domain - Exception: Connection refused https://google.orgi Status:-> Danger <- Wrong domain - Exception: google.orgi https://in.yahoim.com/ Status:-> Danger <- Wrong domain - Exception: in.yahoim.com https://www.amazoni.in/ Status:-> Danger <- Wrong domain - Exception: Connect timed out https://www.amazoni.in/ Status:-> Danger <- Wrong domain - Exception: Connect timed out http://exampleserver.co.in/ Status:-> Danger <-Wrong domain - Exception: exampleserver.co.in http://myserver.com/ Status:-> Danger <- Wrong domain - Exception: myserver.com https://knf.com/ Status:-> Success <- Code: 200 http://wordpresses.jcom/ Status:-> Danger <- Wrong domain - Exception: wordpresses.jcom http://wordpress.jorg/ Status:-> Danger <- Wrong domain - Exception: wordpress.jorg http://example.co.india/ Status:-> Danger <-Wrong domain - Exception: example.co.india http://trycatch.jedu/ Status:-> Danger <- Wrong domain - Exception: trycatch.jedu https://ebay.jco.jcom/ Status:-> Danger <- Wrong domain - Exception: ebay.jco.jcom http://google.jco.juk/ Status:-> Danger <- Wrong domain - Exception: google.jco.juk http://localhost:8080 Status:-> Danger <- Wrong domain - Exception: Connection refused Task completed... Total execution time: 14093

See here we checked the ping status of some HTTP endpoints without multiple threads, Total execution time is 14093 millisecond. In the programming field, it is a sizably voluminous time.

But using multiple threads we can improve the performance✌ Let me show you one example,

Example 2: How to ping multiple HTTP endpoints by run Multiple Threads Concurrently?


package com.knowledgefactory.tutorial;

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://localhost:9091/restTemplateGetTest",
"http://localhost:9091/",
"http://localhost:8080/", "https://google.orgi",
"https://in.yahoim.com/", "https://www.amazoni.in/",
"https://www.amazoni.in/", "http://exampleserver.co.in/",
"http://myserver.com/", "https://knf.com/",
"http://wordpresses.jcom/", "http://wordpress.jorg/",
"http://example.co.india/",
"http://trycatch.jedu/", "https://ebay.jco.jcom/",
"http://google.jco.juk/", "http://localhost:8080" };
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);
HttpURLConnection connection = (HttpURLConnection) siteURL.
openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(4000);
connection.connect();

code = connection.getResponseCode();
if (code == 200) {
result = "-> Success <-\t" + "Code: " + code;
;
} else {
result = "-> Warning <-\t" + "Code: " + code;
}
} catch (Exception e) {
result = "-> Danger <-\t" + "Wrong domain - Exception: " +
e.getMessage();

}
System.out.println(url + "\t\tStatus:" + result);
}
}
}

Output:

http://trycatch.jedu/ Status:-> Danger <- Wrong domain - Exception: trycatch.jedu http://wordpresses.jcom/ Status:-> Danger <-Wrong domain - Exception: wordpresses.jcom http://google.jco.juk/ Status:-> Danger <- Wrong domain - Exception: google.jco.juk http://wordpress.jorg/ Status:-> Danger <- Wrong domain - Exception: wordpress.jorg http://exampleserver.co.in/ Status:-> Danger <-Wrong domain - Exception: exampleserver.co.in http://example.co.india/ Status:-> Danger <-Wrong domain - Exception: example.co.india http://localhost:8080/ Status:-> Danger <- Wrong domain - Exception: Connection refused http://localhost:8080 Status:-> Danger <- Wrong domain - Exception: Connection refused http://localhost:9091/ Status:-> Warning <- Code: 404 http://localhost:9091/restTemplateGetTest Status:-> Success <- Code: 200 https://google.orgi Status:-> Danger <- Wrong domain - Exception: google.orgi https://ebay.jco.jcom/ Status:-> Danger <- Wrong domain - Exception: ebay.jco.jcom https://in.yahoim.com/ Status:-> Danger <- Wrong domain - Exception: in.yahoim.com http://myserver.com/ Status:-> Danger <- Wrong domain - Exception: myserver.com https://knf.com/ Status:-> Success <- Code: 200 https://www.amazoni.in/ Status:-> Danger <- Wrong domain - Exception: Connect timed out https://www.amazoni.in/ Status:-> Danger <- Wrong domain - Exception: Connect timed out Finished all threads Total execution time: 4239

See here we checked the ping status of some HTTP endpoints with multiple threads, Total execution time is 4239 millisecond

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

Comments