0% found this document useful (0 votes)
8 views11 pages

Process Vs Thread in Java

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views11 pages

Process Vs Thread in Java

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Process:-

A process is a program in execution. It is the basic unit of resource allocation and


scheduling by the operating system.
 A process consists of the program code, current activity (values of the
program counter, registers), stack (function calls, local variables), data
section (global variables), and the heap (dynamically allocated memory).
 Each process has its own separate address space and runs independently of
other processes.
 The operating system uses processes to provide isolation and protection
between different running programs.
Thread:-
A thread is the smallest unit of CPU execution within a process. It is sometimes
called a “lightweight process.”
 A thread has its own program counter, register set, and stack, but it shares
the code section, data section, and other resources (such as open files) with
other threads belonging to the same process.
 Multiple threads within a process enable parallelism and faster context
switching while sharing memory and resources.
Process:-
A process is an instance of a program running in memory. Think of it as a whole
house:
 It has its own land and walls (its own private memory/address space).
 It owns its furniture and keys (open files, network sockets, environment,
heap).
 What happens inside the house doesn’t directly touch other houses.
If a process crashes, only that house collapses—your other houses (other
processes) are still fine.
Thread:-
A thread is a worker inside a single house (inside one process):
 All workers share the same rooms and furniture (same memory, files,
heap).
 Each worker has their own toolbox (own registers & stack).
 Workers can talk quickly because they are in the same house (share data
easily).
If a thread misbehaves badly (e.g., corrupts shared memory), it can bring down the
whole house (the entire process).
Differences:-

Aspect Process Thread

Shared within the process


Memory Private to each process (code/heap/file handles), but
each thread has its own stack

Strong isolation; one Weak isolation; one bad thread


Isolation & Safety
crashing rarely kills others can crash the whole process

Creation/Teardown Heavier (more OS work) Lighter (faster to create)

Slower/complex: pipes, Fast & simple: shared


Communication sockets, shared memory variables, queues (needs
(IPC) synchronization)

OS schedules processes (and


Scheduling OS schedules threads
their threads)

Context Switch
Higher Lower
Cost

Security Better boundaries Weaker boundaries

You need isolation, different You need speed, shared state,


Use When languages/runtimes, high responsive UIs, many small
reliability tasks
Simple Real-World Examples
1. Restaurant
o Process = The entire restaurant (kitchen, billing, storage).
o Threads = Chefs/waiters working inside that restaurant.
o Two different restaurants don’t share kitchens (processes don’t share
memory).
o Chefs in the same restaurant can quickly share ingredients (threads
share memory).
2. Web Browser
o Many modern browsers use multiple processes for stability (often
one process per tab/site).
o Inside each tab’s process, there are threads: UI thread, network
thread, rendering thread.
o If one tab’s process dies, other tabs live on; if one thread in a tab
deadlocks, the tab may freeze.
3. Music App on Your Phone/PC
o One process for the app.
o Threads: UI thread (buttons), audio thread (playback), network thread
(stream).
o Audio must not block on slow network; threads keep the app
responsive.

4. Databases/Servers
o PostgreSQL: typically uses one process per client connection
(isolation).
o Java app servers: often use thread pools inside one process to
handle many requests (speed).
How the OS Sees Them (in simple words)
 The OS gives every process its own virtual address space (private
memory).
 Threads live inside a process and share that address space.
 Both are independently scheduled on CPU cores, but switching between
processes is typically costlier than switching between threads.

Communication & Synchronization


 Between Processes (IPC): use pipes, message queues, sockets, shared
memory. It’s safer but more boilerplate and slower to set up.
 Between Threads: share variables directly, but you MUST prevent races:
o Use synchronized, locks, atomics, volatile, semaphores, or queues.
o Risks: race conditions, deadlocks, starvation, livelock.

Performance & Reliability Trade-offs


 Processes: more reliable isolation; if one crashes or leaks memory, others
are safe. Slightly more overhead to create and to communicate.
 Threads: low overhead, fast data sharing → great performance for many
small tasks; but a bug (e.g., bad pointer access/unsynchronized write) can
crash the whole app.
When to Use Which (rule of thumb)
Use Threads when:
 You need responsiveness (e.g., UI thread + worker threads).
 Tasks share a lot of common data (in-memory cache, queues).
 You want high throughput with thread pools handling many I/O requests.
Use Processes when:
 You need strong isolation (run untrusted or crash-prone tasks separately).
 You combine different languages/runtimes or conflicting library versions.
 You build a fault-tolerant system (one worker dies, supervisor restarts it).
 You want to scale across machines easily (processes talk over sockets).
Deep but Simple: Memory Picture
Inside one process:
 Shared by all threads: code, heap (objects), open files/sockets.
 Per thread: program counter, CPU registers, stack (method calls, local
variables).
Across processes:
 Each has its own heap and stacks, so they cannot read each other’s
memory directly (the OS stops them).
Common Pitfalls (and how to avoid)
 Threads
o Race conditions: two threads update the same data at the same time →
use locks/atomics.
o Deadlocks: circular waiting for locks → use lock ordering, timeouts,
or try-lock strategies.
o Blocking the UI thread: long work on UI thread freezes the app →
offload to worker threads.
 Processes
o IPC complexity: passing data needs serialization (JSON/protobuf) and
protocols → use well-defined message formats.
o Higher overhead: more memory per process; creation is slower → use
process pools or supervisors.
Choosing in Practice (real scenarios)
1. Web server handling thousands of requests
o Use a thread pool (or async I/O) inside one process for speed.
2. Running user-submitted code safely (e.g., online judge)
o Use separate processes (or containers) for strong isolation.
3. Video editor with responsive UI + background rendering
o UI thread + worker threads for rendering/encoding.
4. Microservices
o Each service runs as its own process (and often its own container) for
isolation, deployability, and independent scaling.
5. Database engine design
o Some (PostgreSQL) use multi-process for isolation; others use multi-
threading for shared caches and speed. It’s a design trade-off.
1. Multiprogramming
Definition:
Multiprogramming is when multiple programs are loaded into memory at the same
time, and the operating system switches between them to keep the CPU busy.
 Only one program runs on the CPU at a time.
 When one program is waiting (say, for I/O like printing or reading a file), the
CPU quickly switches to another program.
 This increases CPU utilization (no idle time).
Real-World Example:
Imagine you’re cooking in a kitchen:
 You start boiling water (takes time).
 While waiting, you chop vegetables.
 Then you check the water again, and continue cooking.
Here, you = CPU, and boiling water/chopping vegetables = different programs.
You don’t just sit idle—you switch tasks to use time efficiently.

2. Multitasking
Definition:
Multitasking is the ability of an OS to let multiple programs (tasks) run
seemingly at the same time by rapidly switching between them.
 In reality, the CPU gives each program a time slice (tiny fraction of a
second).
 This switching is so fast that it feels like everything runs simultaneously.
 Two types:
o Cooperative multitasking – tasks voluntarily give up control.
o Preemptive multitasking – OS forcibly switches between tasks
(modern OS).
Real-World Example:
On your computer, you:
 Listen to music
 Browse the internet
 Download a file
All these tasks run at the same time (from your perspective). In reality, the CPU is
switching between them super fast.

3. Multithreading
Definition:
Multithreading is when a single program (process) is divided into smaller units
called threads, and those threads run independently but share the same memory.
 Threads within the same process can run in parallel.
 They share resources (memory, files), which makes communication faster.
 Useful when a program needs to do multiple things at once.
Real-World Example:
A web browser (like Chrome):
 One thread handles the UI (buttons, menus).
 Another thread handles downloading files.
 Another renders the webpage content.
If downloading freezes, the UI thread still works, so your browser doesn’t
hang.
Differences:-

Feature Multiprogramming Multitasking Multithreading

Multiple programs in CPU runs A single program


Meaning memory; CPU switches to multiple programs divided into
maximize use seemingly at once multiple threads

Keeps CPU busy during Time-slicing Parallel execution


CPU use
I/O wait between tasks inside one process

Threads share
Programs are
Isolation Programs are separate memory (less
separate
isolated)

Granularity Program-level Program-level Thread-level

Cooking multiple dishes Listening to music Browser: UI,


Real-world
by switching between while typing a rendering, download
analogy
them document threads

Final Simplified View


 Multiprogramming = CPU never sits idle (old technique, batch systems).
 Multitasking = Running many programs at the same time (modern OS,
user-focused).
 Multithreading = Splitting one program into many mini-workers (threads)
that run in parallel.

You might also like