首页 归档 关于 learn love 工具

Concurrency and parallelism in Java

In programming, concurrency is the composition of independently executing processes, while parallelism is the simultaneous execution of (possibly related) computations. Concurrency is about dealing with lots of things at once. Parallelism is about doing lots of things at once.” Source: blog.golang.org

Concurrency is about structure, parallelism is about execution.

Unit of Concurrency

As far as I know, concurrency has three levels:

  • Multiprocessing: Multiple Processors/CPUs executing concurrently. This unit here is a CPU.
  • Multitasking: Multiple tasks/processes running concurrently on a single CPU. The OS executes these tasks by switching between them very frequently. This unit here is a Process.
  • Multithreading: Multiple parts of the same program running concurrently. In this case, we go a step further and divide the same program into multiple parts/threads and run those threads concurrently.

Thread in Java

Creating and Managing Thread

There are two options for creating a Thread in Java. Each thread is created in Java 8 will consume about 1MB as default on OS 64 bit. You can check via command line: java -XX:+PrintFlagsFinal -version | grep ThreadStackSize.

  • Option 1: You can create a class that inherits the Thread.java class.
  • Option 2: You can use a Runnable object.

To create and manage Thread in Java you can use the Executors framework. Java Concurrency API defines three executor interfaces that cover everything that is needed for creating and managing threads:
-** Executor: **launch a task specified by a Runnable object.

  • ExecutorService: a sub-interface of Executor that adds functionality to manage the lifecycle of the tasks.
  • ScheduledExecutor: a sub-interface of ExecutorService that adds functionality to schedule the execution of the tasks.

Most of the executor implementations use thread pools to execute tasks.