Kotlin - 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 Kotlin. 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:

import kotlin.Throws
import kotlin.jvm.JvmStatic
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.lang.Runnable
import KnfPingStatusWithExecutorService.MyRunnable
import java.lang.Exception
import java.net.HttpURLConnection
import java.net.URL

/**
* @author knf
*/
object KnfPingStatusWithExecutorService {
private const val MYTHREADS = 10
@Throws(Exception::class)
@JvmStatic
fun main(args: Array<String>) {
val startTime = System.currentTimeMillis()
val executor = Executors.newFixedThreadPool(MYTHREADS)
val hostList = arrayOf(
"http://localhost:9099/",
"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 (i in hostList.indices) {
val url = hostList[i]
val worker: Runnable = MyRunnable(url)
executor.execute(worker)
}
executor.shutdown()
// Wait until all threads are finish
while (!executor.isTerminated) {
}
println("\nFinished all threads")
val endTime = System.currentTimeMillis()
println("Total execution time: " + (endTime - startTime))
}

class MyRunnable internal constructor(private val url: String) : Runnable {
override fun run() {
var result = ""
var code = 200
try {
val siteURL = URL(url)
val connection = siteURL.openConnection() as HttpURLConnection
connection.requestMethod = "GET"
connection.connectTimeout = 4000
connection.connect()
code = connection.responseCode
result = if (code == 200) {
"-> Success <-\tCode: $code"
} else {
"-> Warning <-\tCode: $code"
}
} catch (e: Exception) {
result = "-> Danger <-\t" + "Wrong domain - Exception: " +
e.message
}
println("$url\t\tStatus:$result")
}
}
}
 

Output:

http://localhost:8080/        Status:-> Danger <-    Wrong domain - Exception: Connection refused (Connection refused)
http://localhost:9091/restTemplateGetTest        Status:-> Danger <-    Wrong domain - Exception: Connection refused (Connection refused)
http://exampleserver.co.in/        Status:-> Danger <-    Wrong domain - Exception: exampleserver.co.in
http://localhost:9091/        Status:-> Danger <-    Wrong domain - Exception: Connection refused (Connection refused)
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://localhost:8080        Status:-> Danger <-    Wrong domain - Exception: Connection refused (Connection refused)
http://trycatch.jedu/        Status:-> Danger <-    Wrong domain - Exception: trycatch.jedu
http://google.jco.juk/        Status:-> Danger <-    Wrong domain - Exception: google.jco.juk
http://myserver.com/        Status:-> Danger <-    Wrong domain - Exception: myserver.com
https://ebay.jco.jcom/        Status:-> Danger <-    Wrong domain - Exception: ebay.jco.jcom
https://in.yahoim.com/        Status:-> Danger <-    Wrong domain - Exception: in.yahoim.com
https://google.orgi        Status:-> Danger <-    Wrong domain - Exception: google.orgi
https://www.amazoni.in/        Status:-> Danger <-    Wrong domain - Exception: No subject alternative DNS name matching www.amazoni.in found.
https://www.amazoni.in/        Status:-> Danger <-    Wrong domain - Exception: No subject alternative DNS name matching www.amazoni.in found.
https://knf.com/        Status:-> Success <-    Code: 200

Finished all threads
Total execution time: 4055

Process finished with exit code 0
 
 
More Kotlin related topics,

Kotlin + Spring Boot CRUD examples:

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