[Go to site: main page, start]

0% found this document useful (0 votes)
10 views22 pages

Java Multi-Threading Basics and Techniques

The document discusses Java multi-threading, covering thread creation methods, lifecycle, and key thread methods such as start(), run(), and sleep(). It explains synchronization, types of locks, and the importance of thread safety, including mechanisms like synchronized blocks and the Executor Framework for managing threads. Additionally, it addresses deadlock scenarios and inter-thread communication methods like wait(), notify(), and notifyAll().

Uploaded by

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

Java Multi-Threading Basics and Techniques

The document discusses Java multi-threading, covering thread creation methods, lifecycle, and key thread methods such as start(), run(), and sleep(). It explains synchronization, types of locks, and the importance of thread safety, including mechanisms like synchronized blocks and the Executor Framework for managing threads. Additionally, it addresses deadlock scenarios and inter-thread communication methods like wait(), notify(), and notifyAll().

Uploaded by

rudrabhaiya.37
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Java Multi-Threading

How JVM Handles Multi-threading?


Thread Lifecycle
Output:

Till now we know that there are two ways of creating threads. First one by extending Thread class and
second one by implementing Runnable interface. But which one to use when??

If there is a class A extending another class B and we have to create a thread of that class A then we
know that we won’t be able to extend it further because of Multiple inheritance not possible in java.
In this case we have to implement Runnable interface.

Thread Methods
1. start(): Starts a thread by calling its run() method in a separate thread of execution.

2. run(): Contains the code that will be executed when the thread is started. You should override this
method in a Thread subclass.

3. sleep(long millis): Pauses the current thread for a specified duration (in milliseconds).
4. currentThread(): Returns a reference to the currently executing thread.

5. isAlive(): Checks whether a thread is still alive (running or ready to run).

6. join(): Waits for the thread to complete its execution.

7. setName(String name) and getName() (1)setName(String name): Sets a name for the thread.
(2)getName(): Retrieves the name of the thread.(3)Naming thread can be done using constructor as
well.
8. interrupt(): Interrupts a thread, signaling it to stop or handle an interruption. This doesn’t
immediately stop the thread but sets its interrupted status to true.

9. setPriority(int priority) and getPriority()

 setPriority(int priority): Sets the thread's priority (range 1 to 10, with Thread.MIN_PRIORITY,
Thread.NORM_PRIORITY, and Thread.MAX_PRIORITY as constants).
 getPriority(): Retrieves the thread's priority.

10. yield(): Hints to the thread scheduler that the current thread is willing to pause its execution and
let other threads run.
11. setDaemon(boolean isDaemon) and isDaemon()

Definition:

 setDaemon(boolean isDaemon): Marks the thread as a daemon thread (a low-priority thread


that runs in the background). For Daemon threads JVM does not waits for there completion.
 isDaemon(): Checks if a thread is a daemon thread.

12. checkAccess(): Verifies if the current thread has permission to modify the thread object.

Synchronization
In Java, synchronized is a keyword used to control access to critical sections of code, ensuring that only
one thread can execute a block of code or method at a time. This prevents race conditions and ensures
thread safety when multiple threads access shared resources.

Types of Synchronization

1. Method Synchronization (Locks on the current object or class)


2. Block Synchronization (Locks only the critical section)
Synchronized Methods: When a method is declared as synchronized, the thread must acquire the lock
on the object (or class for static methods) before executing the method.

Output:

Synchronized Blocks: A synchronized block locks only the specified part of the code. It allows fine-
grained control, so other parts of the object can still be accessed by other threads.
Static Synchronization: If a method is declared static and synchronized, the lock is applied on the class
object rather than an instance.

Locks
locks are mechanisms used to synchronize access to shared resources to prevent race conditions and
ensure thread safety. Java provides several types of locks, including implicit locks (synchronized
blocks/methods) and explicit locks (from the [Link] package).
Types of Locks in Java

1. Implicit Locks (Intrinsic Locks):


o These are built into every object in Java, you don’t see them but they’re there.
o Provided by the synchronized keyword.
o Automatically acquired and released when a synchronized block/method is entered and
exited.
o Example: synchronized methods or blocks.
2. Explicit Locks:
o These are more advanced locks you can control using the Lock interface from
[Link] package.
o Explicitly acquired and released, giving more control to the programmer.
o Types:
 ReentrantLock
 ReadWriteLock
 StampedLock

1. ReentrantLock: ReentrantLock is a lock that allows the same thread to acquire the lock multiple
times (reentrant behavior). It provides more advanced locking mechanisms than the synchronized
keyword, such as fairness policies and interruptible lock acquisition.

 Reentrant capability: The same thread can lock it multiple times and must unlock it the same
number of times.
 Can be fair or unfair (default).
 Supports conditions using Condition objects for more fine-grained thread communication.
Output: Thread-1 acquired the lock.
Thread-1 released the lock.
Thread-2 acquired the lock.
Thread-2 released the lock.

Imp Methods:

1. lock(): Acquires the lock.


2. unlock(): Releases the lock.
3. tryLock(): Attempts to acquire the lock without blocking. Avoids blocking if the lock is
unavailable, suitable for non-critical operations.
4. tryLock(long time, TimeUnit unit): Attempts to acquire the lock within a given timeout. Adds
flexibility by allowing a thread to wait for a limited time, avoiding indefinite blocking.

fairness in locks determines how threads acquire the lock when multiple threads are competing for it.
The concept of fairness ensures that threads access the lock in a fair, first-come, first-served (FIFO)
order.

When creating a ReentrantLock, you can specify whether it should use a fair or unfair policy:

 Fair Lock: Threads acquire the lock in the order they requested it (FIFO). No thread is starved.
 Unfair Lock (default): Threads may "cut in line" and acquire the lock even if other threads were
waiting longer. This can improve throughput but might lead to thread starvation.

Key Methods in Fairness

 ReentrantLock(boolean fair): Pass true to create a fair lock and false (default) for an unfair lock.
 Fair Lock ensures fairness but might reduce overall performance due to frequent context
switching.

2. ReadWriteLock: ReadWriteLock allows multiple threads to read a resource simultaneously while


providing exclusive access to a single thread for writing. It improves performance by allowing multiple
readers when no writer is active.

 Provides two locks: read lock (shared) and write lock (exclusive).
 If a thread holds a write lock, no other thread can acquire a read or write lock.
Output: Writer writing value: 10
Reader-1 read value: 10
Reader-2 read value: 10

3. StampedLock: StampedLock is an advanced lock introduced in Java 8. It improves performance by


reducing the overhead of thread contention. It provides three modes of access:

1. Optimistic read: Non-blocking, allows reading without acquiring the lock.


2. Pessimistic read: Acquires a read lock like ReadWriteLock.
3. Write lock: Acquires an exclusive write lock.

Key Features:

 Optimistic read locks allow lightweight, non-blocking reads, but require validation.
 Provides better performance under low contention compared to ReadWriteLock.
Deadlock: Deadlock is a situation in multithreading where two or more threads are blocked forever,
waiting for each other to release a resource. This typically occurs when two or more threads have
circular dependencies on a set of locks.
Explanation

 Task1 acquires pen first, then tries to acquire paper.


 Task2 acquires paper first, then tries to acquire pen.
 If both threads acquire one resource each, they will both wait forever for the other resource to
be released. This results in a deadlock.
In a Multi threaded environment, threads often need to communicate and coordinate with each other
to accomplish a task. Without proper communication mechanisms, threads might end up in inefficient
busy-waiting states, leading to wastage of CPU resources and potential deadlocks.

Wait(), notify(), notifyAll() methods help in inter-thread communication. Wait() must be called within
a synchronized block or method; otherwise, it throws IllegalMonitorStateException. Implementation
of notify() and notifyAll() is exactly same, its just there internal working is different.
Thread safety in Java means that a piece of code or an object can be safely accessed by multiple threads
simultaneously without causing unexpected behavior, data corruption, or race conditions.

When a class, method, or object is thread-safe, multiple threads can use it without interfering with
each other or leading to inconsistent data. To achieve thread safety we can use:
1. Synchronized keyword
2. Using volatile keyword
3. Using Atomic Variables (from [Link])
4. Using Lock from [Link]
[Link] Concurrent Collections ([Link])
6. By making objects immutable
It is very easy to create a thread now.

Thread Pool: Collection of pre-initialized threads that are ready to perform a task.
Executors Framework:

Problems which are resolved after this:


1. Manual Thread Management
2. Resource Management
3. Scalability
4. Thread Reuse
5. Error Handling

Executor Framework has 3 core interfaces:

You might also like