1. Parallel streams (parallelStream): simple and handy
If you’ve already worked with the Stream API, you know how convenient it is to filter, transform, and collect collections. An important bonus: any stream can be made parallel with literally one line—enable parallel(), and the elements of the collection will start being processed concurrently.
This is especially useful for independent operations over a set of files: count lines, find a substring, copy, compress, etc.
Example: parallel line count across all files in a directory
Option 1: sequential
import java.nio.file.*;
import java.io.IOException;
import java.util.List;
public class LogLineCounter {
public static void main(String[] args) throws IOException {
Path logDir = Paths.get("logs");
long totalLines = 0;
try (DirectoryStream<Path> stream = Files.newDirectoryStream(logDir, "*.log")) {
for (Path file : stream) {
long lines = Files.lines(file).count();
totalLines += lines;
}
}
System.out.println("Total lines across all logs: " + totalLines);
}
}
Note: everything is done in sequence, one file after another. If there are many large files, you’ll have to wait a long time.
Option 2: in parallel!
import java.nio.file.*;
import java.io.IOException;
import java.util.stream.Stream;
public class LogLineCounterParallel {
public static void main(String[] args) throws IOException {
Path logDir = Paths.get("logs");
try (Stream<Path> files = Files.list(logDir)) {
long totalLines = files
.filter(path -> path.toString().endsWith(".log"))
.parallel() // here’s the magic!
.mapToLong(file -> {
try (Stream<String> lines = Files.lines(file)) {
return lines.count();
} catch (IOException e) {
e.printStackTrace();
return 0L;
}
})
.sum();
System.out.println("Total lines across all logs: " + totalLines);
}
}
}
Note: the key line is .parallel(). On a multi-core CPU, the program will generally run noticeably faster.
How does it work?
- parallel() turns a regular stream into a parallel one. Under the hood, it uses the common ForkJoinPool (by default, as many threads as there are cores).
- Each file is processed independently; results are aggregated via terminal operations (for example, sum()).
- If there are few files—you might not see a speedup; if there are hundreds—the gain is usually noticeable.
Important!
- Parallel streams don’t make I/O operations themselves faster; they let you perform several operations at the same time. On fast storage (SSD) this helps; on slow storage (HDD) you can hit a disk “bottleneck.”
2. ForkJoinPool: “divide and conquer” in practice
ForkJoin is a framework for “divide and conquer” parallel computations: split a big task into subtasks, execute them in parallel, and merge the results. A special pool—ForkJoinPool—manages this. It’s exactly what parallel streams use behind the scenes, but you can control it directly for more flexibility.
This model is especially good for recursive structures (directory trees), large data arrays, and tasks that can be easily decomposed into independent parts.
Example: recursive search over a directory tree
Let’s find all ".txt" files (including nested folders) and count the total number of lines.
import java.nio.file.*;
import java.util.concurrent.*;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;
public class FolderLineCounter extends RecursiveTask<Long> {
private final Path dir;
public FolderLineCounter(Path dir) {
this.dir = dir;
}
@Override
protected Long compute() {
List<FolderLineCounter> subTasks = new ArrayList<>();
long lines = 0;
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
for (Path entry : stream) {
if (Files.isDirectory(entry)) {
FolderLineCounter task = new FolderLineCounter(entry);
task.fork(); // Launch a subtask
subTasks.add(task);
} else if (entry.toString().endsWith(".txt")) {
try (Stream<String> fileLines = Files.lines(entry)) {
lines += fileLines.count();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
// Gather results from subtasks
for (FolderLineCounter task : subTasks) {
lines += task.join();
}
return lines;
}
public static void main(String[] args) {
Path root = Paths.get("big_folder");
ForkJoinPool pool = new ForkJoinPool();
FolderLineCounter counter = new FolderLineCounter(root);
long totalLines = pool.invoke(counter);
System.out.println("Total lines across all .txt files: " + totalLines);
}
}
What happens here:
- A separate task (FolderLineCounter) is created for each folder; for subdirectories—their own subtasks (fork()).
- Files are counted in place; results are summed after join() of all subtasks.
What are the advantages of ForkJoin?
- Works efficiently with large hierarchies (directory trees).
- Maximally loads CPU cores.
- Allows fine control over parallelization and task granularity.
3. Practical usage scenarios
Bulk file processing
For example, you need to copy thousands of photos to a backup folder.
import java.nio.file.*;
import java.util.List;
import java.util.stream.Collectors;
public class ParallelFileCopier {
public static void main(String[] args) throws Exception {
Path sourceDir = Paths.get("photos");
Path destDir = Paths.get("photos_backup");
Files.createDirectories(destDir);
List<Path> files = Files.list(sourceDir)
.filter(Files::isRegularFile)
.collect(Collectors.toList());
files.parallelStream().forEach(file -> {
try {
Path destFile = destDir.resolve(file.getFileName());
Files.copy(file, destFile, StandardCopyOption.REPLACE_EXISTING);
} catch (Exception e) {
e.printStackTrace();
}
});
System.out.println("All files have been copied!");
}
}
Note: each file is copied in a separate thread. With many files, the speedup is noticeable.
Parallel compression/decompression
Similarly, you can parallelize compression, recomputing hashes, image format conversion, etc., via parallelStream() or your own ForkJoinPool.
4. Important notes and limitations
- I/O operations don’t always benefit from parallelism. If the disk or network is the bottleneck, a hundred parallel tasks will only increase contention for the resource.
- Don’t spawn too many threads. By default, parallel streams use the common ForkJoinPool.commonPool() with a parallelism level ≈ the number of cores. You can change it via the property "java.util.concurrent.ForkJoinPool.common.parallelism", but do so deliberately.
- Don’t forget about synchronization. If multiple threads write to the same file/object—use synchronization and queues; for independent files—no synchronization is needed.
5. A quick look at FileChannel and positional access
For advanced scenarios (for example, parallel reading of different parts of a single large file), use java.nio.channels.FileChannel, which supports positional reads/writes.
Example: reading different parts of a file in different threads
import java.nio.channels.FileChannel;
import java.nio.file.*;
import java.nio.ByteBuffer;
public class FileChunkReader implements Runnable {
private final Path path;
private final long position;
private final int size;
public FileChunkReader(Path path, long position, int size) {
this.path = path;
this.position = position;
this.size = size;
}
@Override
public void run() {
try (FileChannel channel = FileChannel.open(path, StandardOpenOption.READ)) {
ByteBuffer buffer = ByteBuffer.allocate(size);
channel.read(buffer, position);
// Process data
System.out.println("Read " + buffer.position() + " bytes from position " + position);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Note: run several such tasks—each reads its own range. But be careful: not all disks and file systems like heavy parallel load.
6. Common mistakes in parallel file processing
Error #1: parallel writes to a single file without synchronization. Data gets interleaved and corrupted. Use queues, buffering, and synchronized writes.
Error #2: too much parallelism. Parallel streams on modest hardware or tiny files add overhead and can slow execution down.
Error #3: ignoring I/O errors. In parallel streams, exceptions are easy to “lose”—handle them inside lambdas, log them, and account for failures.
Error #4: unclosed resources. Always use try-with-resources for streams/channels; otherwise you’ll get leaks and odd errors.
Error #5: expecting “magic” from parallel(). Parallelism speeds things up only when there’s enough work and available resources (CPU, fast disk). The parallel() call itself is not a silver bullet.
GO TO FULL VERSION