Day 11 of 100 - Java: Concurrency
Published: 2022-01-19 12:32:52



### What is a process vs thread

Processes do not share common memory
Threads share common memory

A process is an isolated piece of software, work by inter-process communication called as intermediate API.

A thread shares memory with threads of the same application, it allows for reducing overhead, and faster data exchange.

### Create a thread instance

A thread is a thread of execution in a program.

- Threads have priorities
- Code running in some thread creates a new `Thread` object, initial priority is equal to the creator thread
- Thread execution continues until
    - the `exit` method of class `Runtime` has been called, with security manager's permission.
    - All the non-daemon threads have died

Declare a class to be a subclass of `Thread`. This subclass should override the `run` method of class `Thread`.

```java
class PrimeThread extends Thread {
  long minPrime;
  PrimeThread(long minPrime) {
    this.minPrime = minPrime;
  }

  public void run() {
    // compute logic goes here
  }
}

PrimeThread p = new PrimeThread(143);
p.start();
```

https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/concurrent/package-summary.html

or simply call from `Runnable`

```java
Thread thread01 = new Thread(() -> System.out.println("Hello"));
thread01.start();
```

### Thread states

https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Thread.State.html

- NEW - A thread that has not yet started in this state.
- RUNNABLE - A thread executing in the Java virtual machine in this state
- BLOCKED - A thread that is blocked waiting for a monitor lock in this state
- WAITING - A thread waiting indefinitely for another thread to perform a particular action. A variant is TIMED_WAITING.
- TERMINATED

### Runnable vs Callable interfaces

`Runnable` has a `run` method. Runs a unit of computation in a thread

`Callable` interface has a `call` method and returns a value.

### Create a daemon thread

Daemon threads do supportive tasks for the other threads, and can be abandoned at anytime.

```java
Thread daemon = new Thread(() -> System.out.println("This is a daemon thread");

daemon.setDaemon(true);
daemon.start();
```

https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Thread.html#isDaemon()

### Implementations of `ExecutorService`

`ForkJoinPool`, `ScheduledThreadPoolExecutor`, `ThreadPoolExecutor`

### Java memory model (JMM)

Important for the interaction among threads.

Some notions of JMM
- Actions, are inter-thread. They can be executed by one thread and found by another.
- Program Order, the observable total order of actions in a single thread
- Synchronization Order, the total order between all synchronization actions - in consistent with Program Order.
- Execution - a certain set of ordered actions with consistency rules among them

If a program is synchronized then all of its execution have sequentially consistent.

### Deadlock, Livelock and Starvation

> Two processes each waiting for a resource the other has but waiting in a non-blocking manner. When each learns they cannot continue they release their held resource and sleep for 30 seconds, then they retrieve their original resource followed by trying to the resource the other process held, then left, then reacquired Since both processes are trying to cope (just badly), this is a livelock.

https://stackoverflow.com/a/6155978/7860306