Java is a multi-threaded language. Since the beginning of the language it had first class support of multiple threads for our concurrency needs. After that with every release of Java the multi-thread model has been simpler and more accessible to users. From ThreadPoolExecutorFuture in Java 5 to CompletableFutureForkJoin framework etc in Java 8. Also powerful third-party frameworks like RxJava evolved in the wild.

Though these abstractions make concurrency more available to the average user, one still should learn about the nuts and bolts of the language (and JVM). It will help clear the picture of concurrency and appreciate the skillfully designed concurrency abstractions we use.

Higher level constructs like ThreadPoolExecutorCompletableFutureLatchetc. are intentionally omitted.

THREAD

A thread is a thread of execution in a program. You can run as many threads in parallel as many CPU cores you have. Although there can be hundreds of them in the waiting state. A thread represents a system thread as provided by the underlying OS (in most JVM implementations). Just like processes in an OS, threads are scheduled and have a life-cycle.

A thread can be created by creating a thread object and passing a runnableto it. Bear in mind creating a runnable does not create a thread. If you only create a runnable and run it directly it will just be executed by the current thread.

Threads can also be set daemon, meaning JVM can exit while these threads are running.

public class SimpleThreadExample {
	    public static void main(String[] args) {
	        new Thread(new Runnable() {
	            @Override
	            public void run() {
	                System.out.println("This is " + Thread.currentThread().getName());
	            }
	        }).start();
	        System.out.println("And this is "+Thread.currentThread().getName());
	    }
	}

#multithreading #concurrency #java

Low-Level Concurrency in Java
2.00 GEEK