Quiz: Multithreading in Java: Processes and Threads
Study the lesson first: Multithreading in Java: Processes and Threads
Total: 6 questions
1. What is multithreading in Java, and how does it differ from multitasking?
What is multithreading in Java, and how does it differ from multitasking?
Multithreading is the concurrent execution of several threads inside a single process. A thread is an independent sequence of instructions with its own call stack; all threads of a process work with a shared heap and can process the same data together. In Java a thread is represented by the java.lang.Thread class, and every program starts with at least one thread, main.
Multitasking is the broader idea: a system's ability to run several tasks at the same time. It comes in two kinds:
- process-based — different programs run side by side, each with its own address space; communication and context switching between processes are expensive;
- thread-based — one program performs several tasks; threads share the process's address space, so communication and switching between them are cheaper.
Multithreading is the second kind: multitasking inside a single process. A real-world example is a web browser: tabs often run in separate processes, and inside a tab different threads load images, run scripts and render the page.
2. What is the difference between a process and a thread in Java?
What is the difference between a process and a thread in Java?
A process is a running program with its own isolated memory. A thread is a unit of execution inside a process that shares memory with the other threads of the same process.
- Memory: a process has its own address space; a thread owns only its stack, the heap is shared.
- Creation and context switch: expensive for a process — the OS allocates memory and the address space changes; cheaper for a thread, and cheaper still for a virtual thread.
- Communication: processes talk through OS facilities — files, sockets, pipes; threads use shared objects on the heap, which is fast but requires synchronization.
- Fault isolation: a crashed process doesn't affect the others; corrupted shared data is seen by every thread, and an
OutOfMemoryErrororSystem.exit()affects the whole JVM.
In Java a process is a running JVM (a new process is launched with ProcessBuilder), and a thread is a Thread object started with start(). An unhandled exception ends only its own thread: the console shows Exception in thread "Thread-0" ..., while the other threads, including main, keep running.
3. What do the threads of one Java process share, and what does each thread own?
What do the threads of one Java process share, and what does each thread own?
Shared by all threads of a process:
- the heap — every object the threads hold references to;
- object fields and static fields of classes;
- process resources — open files, network connections.
Owned by each thread: its call stack with method parameters and local variables, and its program counter (the place in the code the thread is executing right now). That's why two threads can run the same method at the same time, each with its own copy of the local variables.
Hence the main rule: everything on the heap that several threads can reach must be protected, while a method's local variables need no protection (but the object a local variable refers to lives on the heap and may be shared). The word “thread” in Java means both a thread of execution and a java.lang.Thread object: you can create the object and never start it, and the thread of execution appears only after start() is called.
4. What is the difference between concurrency and parallelism?
What is the difference between concurrency and parallelism?
Concurrency means several tasks are in progress during the same period of time, but they may run in turns, a slice at a time. Parallelism means tasks literally run at the same instant on different CPU cores. Parallelism is a special case of concurrency.
A multithreaded program on a single-core CPU is concurrent but not parallel: the scheduler switches the core between threads quickly. On a multi-core CPU the same threads can run in parallel. Synchronization bugs show up in both cases, because a thread can be interrupted between any two instructions, but only real parallelism speeds up computation.
Example: a web server handling hundreds of connections on one core is concurrency; parallelStream() spreading the sum of a large array across all cores is parallelism.
5. When does multithreading speed a program up, and how many threads should you create?
When does multithreading speed a program up, and how many threads should you create?
Multithreading speeds things up only if the task waits on I/O, or if there are enough free cores for all the compute threads:
- I/O-bound (HTTP requests, database calls, reading files) — a big win: while some threads wait for a response, others keep working; you can have far more threads than cores;
- CPU-bound (compression, image processing, math over large arrays) — the speedup is no greater than the number of cores, and extra threads only add context switches;
- an inherently sequential task, where each step depends on the previous one, doesn't speed up at all.
For computation, use roughly as many threads as there are cores: Runtime.getRuntime().availableProcessors(). For tasks that wait, use more; the well-known estimate from “Java Concurrency in Practice” is cores × (1 + wait time / compute time), and the exact number is tuned by measuring under load. For thousands of concurrent requests on Java 21, virtual threads are the usual choice instead of a huge pool of platform threads.
Threads have a cost: memory for the stack, a system call to create one, context switches and waiting on synchronization. If threads keep waiting for each other, the multithreaded version can turn out slower than the single-threaded one.
6. What problems does multithreading bring?
What problems does multithreading bring?
The main bugs in multithreaded code grow out of shared memory:
- race condition — threads modify shared data at the same time, and some of the changes are lost;
- visibility — a thread doesn't see a write made by another thread, or sees it late;
- deadlock — threads wait forever for resources held by each other; the program hangs with no exception;
- starvation — a thread goes a long time without getting the CPU or a resource because others keep taking it;
- livelock — threads are busy, but keep yielding to each other forever and make no progress.
The compiler doesn't catch these bugs, and the result depends on how the scheduler interleaves the threads: a test that passed a hundred times can fail on the hundred-and-first run, and a bug seen on the server won't reproduce on the developer's machine. That's why multithreaded code is designed to keep shared mutable state to a minimum.