In Intermediate Java, we learned how to implement concurrent threading by using Threads and Synchronization. We’ll cover a few more implementations for that, however, under normal circumstances, most multithreading performed in Java is processed on a single stream.
Java 7 provides a Fork-Join framework to enable parallel computing, but it requires you to specify exactly how the problems are subdivided. To truly incorporate parallelism into our programs, we need to utilize multiple streams, which is a Java 8+ feature. We’ll discuss exactly what that means later in this lesson.
For now, let’s quickly recap the definitions for concurrency and parallelism:
- Concurrency is the act of processing more than one task at seemingly the same time on the same CPU, requiring the ability to switch between tasks.
- Parallelism is the act of splitting tasks into smaller subtasks and processing those subtasks in parallel, for instance across multiple CPUs at the exact same time.
Java is very particular about how it allocates its resources for threading. For instance, the JVM understands your static
main runner as a
main thread whenever you run your projects. You can see a demonstration of this by implementing the following print statement into any project’s static
System.out.println(“Thread name: “ + Thread.currentThread().getName());
The following will be printed out:
Thread name: main
Whenever we create additional threads, either through extending
Thread or implementing
Runnable, they will all run concurrently (including the main thread). This is because the JVM likes to keep a process’s running threads in the same place by default.
It’s important to note that concurrent threading isn’t a bad thing, and parallelism should not be considered “better.” Each of these concepts has its strengths and levels of efficiency, and there will always be a tradeoff of overhead in both.
Programs that don’t need parallelism should not be forced into it, but do know that sometimes real parallelism will show very real benefits. But before we see how we can actually implement parallelism, let’s cover some open-source frameworks that make concurrent threading much easier to use and keep organized.
Move on when you’re ready!