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.india
http://trycatch.edu/            Status:-> Danger <-    Wrong domain - Exception: trycatch.edu
http://exampleserver.co.in              Status:-> Danger <-   Wrong domain - Exception: exampleserver.co.in
http://wordpress.com/           Status:-> Warning <-   Status Code: 301
http://google.com               Status:-> Success <-   Status Code: 200
http://google.co.uk/            Status:-> Success <-   Status Code: 200
http://wordpress.org/           Status:-> Warning <-   Status Code: 301
http://yahoo.com                Status:-> Warning <-   Status Code: 301
https://ebay.co.in/             Status:-> Danger <-    Wrong domain - Exception: ebay.co.in
https://www.amazon.com          Status:-> Success <-   Status Code: 200
https://www.amazon.in           Status:-> Success <-   Status Code: 200
http://myserver.com             Status:-> Danger <-    Wrong domain - Exception: myserver.com
https://example.com             Status:-> Success <-   Status Code: 200
https://bing.com                Status:-> Success <-   Status Code: 200
https://yandex.com              Status:-> Success <-   Status Code: 200

Finished all threads
Total 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.india
http://trycatch.edu/            Status:-> Danger <-    Wrong domain - Exception: trycatch.edu
http://exampleserver.co.in              Status:-> Danger <-   Wrong domain - Exception: exampleserver.co.in
http://wordpress.com/           Status:-> Warning <-   Status Code: 301
http://google.com               Status:-> Success <-   Status Code: 200
http://google.co.uk/            Status:-> Success <-   Status Code: 200
http://wordpress.org/           Status:-> Warning <-   Status Code: 301
http://yahoo.com                Status:-> Warning <-   Status Code: 301
https://ebay.co.in/             Status:-> Danger <-    Wrong domain - Exception: ebay.co.in
https://www.amazon.com          Status:-> Success <-   Status Code: 200
https://www.amazon.in           Status:-> Success <-   Status Code: 200
http://myserver.com             Status:-> Danger <-    Wrong domain - Exception: myserver.com
https://example.com             Status:-> Success <-   Status Code: 200
https://bing.com                Status:-> Success <-   Status Code: 200
https://yandex.com              Status:-> Success <-   Status Code: 200

Finished all threads
Total execution time: 2511

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete