Interview Q&A · Java · 7 questions in this topic

Processes, Threads and Multitasking — Java Interview Q&A

All Java topics

How processes differ from threads, what multitasking means, and why Java programs use threads. Part of Threads & Concurrency · 294 questions in the Java bank.

What is a process?

Answer

A process is a program in execution that is managed by the operating system. Each process receives its own private memory space for code, data, and resources such as open files and sockets. Because of this isolation, one process cannot directly read or corrupt the memory of another process. That safety makes processes heavyweight, since creating them and switching between them is relatively expensive.

What is a thread?

Answer

A thread is an independent path of execution that runs inside a process. All threads of a process share the same memory and resources, so they can communicate by reading and writing shared objects. Each thread has only its own stack and program counter, which makes threads lightweight compared to processes. The trade-off is that shared memory must be coordinated carefully to avoid race conditions.

Process vs thread?

Answer

A process owns a separate address space, while all threads of a process share the same address space. Processes are isolated and heavyweight, whereas threads are lightweight and start and switch faster. Threads can communicate cheaply through shared memory, while processes need slower mechanisms such as pipes or sockets. For this reason, threads suit fine-grained concurrent work inside one application, and processes suit isolation between independent programs.

Key points

  1. 1Weight: processes are heavyweight, threads are lightweight.
  2. 2Address space: each process has its own space, threads of a process share one space.
  3. 3Communication: threads share memory directly, processes need inter-process communication.
  4. 4Context switch: switching processes costs more than switching threads of the same process.

Learn this topic

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits