- Published on
Concurrency and Parallelism in Functional Programming with Java
- Authors
- Name
- Gary Huynh
- @huynhthienthach
Ahoy, fellow Java
-nauts! Buckle up, because we're about to enter the warp speed zone of Concurrency
and Parallelism
! That's right, we're not content with running our code at a measly normal pace - no, we're Java
programmers, and we want our code to run like it's on an espresso shot!
When you think of concurrent and parallel programming in Java
, you might get visions of nightmarish threads
, locks
, and race conditions
. But with functional programming
, you can toss those worries out the window and cruise through concurrency
like a sports car on an open highway!
Let's start with CompletableFuture
. CompletableFutures
are like that multi-tasking
friend who can juggle, eat pizza, and solve a Rubik's cube all at once. These guys can handle multiple tasks concurrently
and give you the result when all tasks are done.
Let's say you want to download cat pictures and dog pictures at the same time (because who doesn't?) but they can be downloaded independently of each other. Here's how you'd do it:
CompletableFuture<List<CatPicture>> catPictures = downloadCatPictures();
CompletableFuture<List<DogPicture>> dogPictures = downloadDogPictures();
CompletableFuture.allOf(catPictures, dogPictures)
.thenAccept(v -> {
List<CatPicture> cats = catPictures.join();
List<DogPicture> dogs = dogPictures.join();
System.out.println("Look at all these pictures: " + cats.size() + " cats and " + dogs.size() + " dogs!");
});
Just like that, you've got yourself concurrent downloads of cat and dog pictures. Pretty slick, huh?
But what if you want to harness the power of parallelism
for data processing
tasks? Enter Parallel Streams
, the Flash of Java
.
Java Streams
are a sequence of elements supporting sequential
and parallel
aggregate operations, kind of like a fancy conveyor belt at a high-tech factory.
You may want to read this post: What is Java Stream?
Let's say you have a list of cat picture URLs
, and you want to download them. With Parallel Streams
, you can download multiple pictures at the same time:
List<CatPicture> catPictures = catPictureUrls.parallelStream()
.map(this::downloadCatPicture)
.collect(Collectors.toList());
Bam! With parallelStream
, your cat pictures download in parallel. This means that if you have four URLs, and you have a quad-core processor (each core for one adorable cat!), you can theoretically download four cat pictures at the same time. Now that's some speed!
So there you have it, brave Java
conquerors! The spooky world of concurrent and parallel programming
isn't so spooky after all, thanks to CompletableFuture
and Parallel Streams
. Remember, with great power comes great responsibility, so use these powers wisely and enjoy the speed!