Java Thread Programming (Part 2)
After discussing the history of threading and how to initiate/begin a thread, now let's look at an illustration of how to leverage threads to our advantage.
Join the DZone community and get the full member experience.
Join For FreeIn a previous post, we discussed the history of threading and provided instructions on how to initiate and begin a thread.
Let's take a look at an illustration of how we might leverage threads to our advantage in this article.
Let's say, for the sake of argument, that we are going to build a web server. For the purpose of this illustration, let's limit ourselves to a single-use case as follows: the web server will listen to requests from any client, and if it detects that a URL has been sent, it will provide a list of the top five words that appear the most frequently on the specified website.
Now that we have our premise established, let's get started with the coding, shall we?
package com.bazlur;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.util.stream.Collectors;
public class SingleThreadedServer {
private final MostFrequentWordService mostFrequentWordService = new MostFrequentWordService();
public SingleThreadedServer(int port) throws IOException {
var serverSocket = new ServerSocket(port);
while (true) {
var socket = serverSocket.accept();
handle(socket);
}
}
private void handle(Socket socket) {
System.out.println("Client connected: " + socket);
try (var in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
var out = new PrintWriter(socket.getOutputStream(), true)) {
String line;
while ((line = in.readLine()) != null) {
if (isValid(line)) {
var wordCount = mostFrequentWordService.mostFrequentWord(line)
.stream()
.map(counter -> counter.word() + ": " + counter.count())
.collect(Collectors.joining("\n"));
out.println(wordCount);
} else if (line.contains("quit")) {
out.println("Goodbye!");
socket.close();
} else {
out.println("Malformed URL");
}
}
} catch (IOException e) {
System.out.println("Was unable to establish or communicate with client socket:" + e.getMessage());
}
}
private static boolean isValid(String stringURL) {
try {
new URL(stringURL);
} catch (MalformedURLException e) {
System.out.println("invalid url: " + stringURL);
return false;
}
return true;
}
public static void main(String[] args) throws IOException {
new SingleThreadedServer(2222);
}
}
First, let's go over the code line by line. The code that you just looked at creates a ServerSocket
that connects to a port and then waits in a loop for clients to connect. The method with the name handle()
is the most crucial one. After obtaining a Socket
object, it begins communicating with the client. It makes a call to a service known as MostFrequentWordService
in order to obtain the most frequent terms whenever a client delivers a valid URL.
Telnet allows us to connect to the server and utilize this host's resources.
The one and only drawback of this solution is that it can only service one client at a time. If we make an attempt to connect a second client, however, it will not react until the first client that was connected is disconnected.
That is most definitely going to be an issue for a web server. It is expected for a web server to establish connections with hundreds or thousands of clients at the same time.
If we convert this application that only has one thread to one that has several threads, we should be able to address this issue really quickly. Remember the handle()
method from the preceding line of code? I am able to start a new thread whenever a client connects, and then I can pass the handle()
method to the thread that I have started.
Did you get it right? That is the secret. Let's do it:
public class MultiThreadedServer {
private final MostFrequentWordService mostFrequentWordService = new MostFrequentWordService();
public MultiThreadedServer(int port) throws IOException {
var serverSocket = new ServerSocket(port);
while (true) {
var socket = serverSocket.accept();
var thread = new Thread(() -> handle(socket));
thread.start();
}
}
//rest of the code.
}
Now, we are able to connect several clients at the same time and provide service to all of them simultaneously:
Now that we have a better understanding of the advantages that come with utilizing threads in Java, we are going to delve a little bit deeper into the topic of using threads in the subsequent articles that are going to be included in this series.
In addition, in the situation that you are curious about the methods in which I developed MostFrequentWordService
, the following is provided:
package com.bazlur;
import org.jsoup.Jsoup;
import java.io.IOException;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
record WordCount(String word, long count) {
}
public class MostFrequentWordService {
public List mostFrequentWord(String url) throws IOException {
var wordCount = Arrays.stream(getWords(url))
.filter(value -> !value.isEmpty())
.filter(value -> value.length() > 3)
.map(String::toLowerCase)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
return wordCount.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.limit(5)
.map(entry -> new WordCount(entry.getKey(), entry.getValue()))
.collect(Collectors.toList());
}
private String[] getWords(String url) throws IOException {
var connect = Jsoup.connect(url);
var document = connect.get();
var content = document.body().text();
return content.split("[^a-zA-Z]");
}
}
Over here, I have successfully extracted text from a website by utilizing the JSoup library. It provides me with a list of terms in an array.
You will need the following dependency in order to use JSoup.
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.15.2</version>
</dependency>
Then I used the Stream API to remove words with fewer than three letters.
Using the Collectors.groupingBy()
method, I counted each latter based on their frequency, then picked the top 5 and returned them.
That's it for today!
Published at DZone with permission of A N M Bazlur Rahman, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments