Video in progress

What is the difference between a process and a thread?

A process is a separate program started by the operating system, with its own memory. A thread is a separate path of execution inside a process: threads in one process share the heap, but each has its own stack.

📖 Answer

Every java -jar app.jar is one process. Inside it, the JVM starts dozens of threads: main, the GC threads, the JIT compiler, Tomcat's http-nio-8080-exec-* threads and so on.

The main differences:

  • processes don't share memory; they talk through IPC (sockets, files, pipes);
  • threads work in the same heap, so passing an object to another thread is free, but this is exactly where race conditions begin;
  • creating a process is expensive, a platform thread is cheaper, and a virtual thread is cheaper still;
  • if one thread dies from an OutOfMemoryError, the whole process is affected.

Every thread has its own stack: local variables and method calls live there. That is why a local variable is never visible to another thread. The problem is only with shared objects on the heap.