Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Challenge Executors | High-level Synchronization Mechanisms
Multithreading in Java
course content

Course Content

Multithreading in Java

Multithreading in Java

1. Multithreading Basics
2. Synchronized Collections
3. High-level Synchronization Mechanisms
4. Multithreading Best Practices

Challenge Executors

Task

Imagine that you have a list of files, each of which contains lines of text. Your task is to read lines from these files in parallel and count the number of words in each line. Use ExecutorService, Future, and a thread pool to accomplish the task.

Requirements:

  • Create a thread pool: Create a fixed-size thread pool using Executors.newFixedThreadPool(int nThreads), where nThreads is the number of threads in the pool;
  • Task Implementation: Implement a WordCountTask class that implements the Callable<String> interface and receives a file as input. In the call method of this class, read lines from the file, count the number of words in each line, and return the result;
  • Using ExecutorService: Using ExecutorService, send jobs to the thread pool for execution. The jobs must use the WordCountTask class.

Note

Also, the string that you form in a separate thread, you must return and use the get() method of the Future interface to get the result of the thread execution and output to the console in the main method.

Read from file

To implement the call() method, you can use BufferedReader to read strings from files. Employ a try-with-resources block so that resources are automatically closed for you.

java

Main

Use the readLine() method to read each line, and be sure to check for null to determine when you've reached the end of the file.

Next, split the string into an array of strings using the split("\\s+") method with the \\s+ pattern, which separates the string by spaces, and then get the size of the array.

In the string itself, which the stream returns, use this formatting

java

Main

Files are already in the project you don't need to create or modify them!

Example output

Everything was clear?

Section 3. Chapter 7
We're sorry to hear that something went wrong. What happened?
some-alt