DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Stop Writing Database Migration Scripts: Declarative Schema Sync for Java
  • Searching Kafka Without an Index: Lessons From Building Message Search for Kafdrop
  • ScyllaDB in Enterprise Java: High-Performance NoSQL With Eclipse JNoSQL
  • Member Spotlight: Shai Almong

Trending

  • Claude Code Superpowers: The 5-Tool Stack That Ends Limits and Context Amnesia
  • How to Keep AI Agents From Going Rogue Using Docker Sandbox
  • Fix the Target, Precompute Once: A Backend-Free Word-Ladder Solver With a BFS Distance Field
  • PostgreSQL vs Oracle: When Higher Cost Means Better Performance

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Java
  4. Java Thread Programming (Part 2)

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.

By 
A N M Bazlur Rahman
DZone Core CORE ·
Jul. 12, 22 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
7.0K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

In 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?

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

Java
 
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:
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:

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

XML
 
<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!

Java (programming language)

Published at DZone with permission of A N M Bazlur Rahman. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Stop Writing Database Migration Scripts: Declarative Schema Sync for Java
  • Searching Kafka Without an Index: Lessons From Building Message Search for Kafdrop
  • ScyllaDB in Enterprise Java: High-Performance NoSQL With Eclipse JNoSQL
  • Member Spotlight: Shai Almong

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook