0% found this document useful (0 votes)
11 views

Java Concurrency

Uploaded by

Deepa Deepa
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Java Concurrency

Uploaded by

Deepa Deepa
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Java : Concurrency

1. Safety Issues

Definition: Safety ensures that concurrent threads do not produce incorrect results or leave the
program in an invalid state. It typically arises due to improper synchronization.

Examples:

 Race Conditions: Two or more threads access shared data at the same time, and at least
one thread modifies the data, causing unpredictable results.
 Data Inconsistency: Improper synchronization leads to shared data being corrupted.

Solutions:

 Use synchronized blocks or methods to protect shared resources.


 Use volatile for visibility of changes to variables across threads.
 Leverage high-level constructs like java.util.concurrent.atomic classes or locks.

2. Liveness Issues

Definition: Liveness refers to the system's ability to make progress. Problems arise when threads
cannot proceed with their tasks.

Examples:

 Deadlock: Two or more threads are waiting for each other's locks, causing an indefinite
halt.
 Starvation: A thread is perpetually denied access to resources due to other high-priority
threads.
 Blocked Threads: A thread is stuck waiting for a condition that will never be met.

Solutions:

 Avoid nested locks or use a consistent lock acquisition order to prevent deadlocks.
 Use ReentrantLock with fairness policies.
 Implement timeouts using methods like tryLock() from ReentrantLock.

3. Fairness Issues
Definition: Fairness ensures that all threads get an opportunity to execute without being starved
by other threads.

Examples:

 Unfair Scheduling: Threads with lower priority or those that have waited longer may be
ignored in favor of others.
 Thread Starvation: When certain threads are perpetually denied CPU time or access to
resources.

Solutions:

 Use ReentrantLock with the fairness flag set to true. For example:

java
Copy code
Lock lock = new ReentrantLock(true); // Fair lock

 Use thread pools from ExecutorService to manage threads more equitably.


 Avoid thread priorities unless necessary, as they can lead to unfair behavior.

Best Practices to Handle Concurrency Issues

1. Prefer High-Level APIs: Use java.util.concurrent package classes like


ExecutorService, ConcurrentHashMap, Semaphore, and CountDownLatch.
2. Immutable Objects: Favor immutability to avoid shared state.
3. Avoid Locks Where Possible: Use non-blocking algorithms or thread-safe data
structures.
4. Debugging Tools: Use tools like Java VisualVM or Thread Dump Analysis to identify
concurrency bottlenecks.

By addressing safety, liveness, and fairness, you can build robust and efficient concurrent
applications in Java.

In Java, locks are mechanisms used to ensure that multiple threads do not access shared
resources concurrently in a way that causes conflicts or inconsistencies. Java provides several
ways to use locks, from basic synchronization primitives to advanced locking mechanisms in the
java.util.concurrent package.

Types of Locks in Java


1. Intrinsic Locks (Synchronized Keyword)

 Every Java object has an intrinsic lock, which can be accessed via the synchronized
keyword.
 Usage:
o Synchronize a method:

java
Copy code
public synchronized void sharedMethod() {
// Critical section
}

o Synchronize a block:

java
Copy code
public void sharedMethod() {
synchronized(this) {
// Critical section
}
}

 Features:
o Simple to use.
o Automatically releases the lock when the thread exits the synchronized block.
o Does not allow try-locking or fairness policies.

2. Explicit Locks (ReentrantLock)

 Found in java.util.concurrent.locks package.


 Provides more advanced locking capabilities compared to intrinsic locks.
 Usage:

java
Copy code
import java.util.concurrent.locks.ReentrantLock;

ReentrantLock lock = new ReentrantLock();

public void sharedMethod() {


lock.lock(); // Acquires the lock
try {
// Critical section
} finally {
lock.unlock(); // Ensures the lock is released
}
}
 Features:
o Allows explicit acquisition and release of locks.
o Supports tryLock(): Attempts to acquire the lock without blocking.

java
Copy code
if (lock.tryLock()) {
try {
// Critical section
} finally {
lock.unlock();
}
} else {
// Handle the case where the lock was not acquired
}

o Supports fair locks: Threads are granted locks in the order they requested.

java
Copy code
ReentrantLock fairLock = new ReentrantLock(true); // Fair policy

Key Lock Features

Reentrancy

 A thread that already holds a lock can reacquire it without causing a deadlock.
 Example: Both synchronized and ReentrantLock are reentrant.

Fairness

 Determines the order in which threads acquire locks.


 Unfair Locks (default): Threads may acquire locks out of order.
 Fair Locks: Threads are granted locks in the order of their requests.

Interruptible Locks

 Explicit locks (e.g., ReentrantLock) support interruptible lock acquisition, allowing a


thread to stop waiting for a lock if interrupted.

Advanced Locking Mechanisms

1. ReadWriteLock
o Provides a pair of locks: one for reading and one for writing.
o Multiple threads can hold the read lock simultaneously, but the write lock is
exclusive.
o Example:

java
Copy code
import java.util.concurrent.locks.ReentrantReadWriteLock;

ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();

public void read() {


rwLock.readLock().lock();
try {
// Reading shared data
} finally {
rwLock.readLock().unlock();
}
}

public void write() {


rwLock.writeLock().lock();
try {
// Writing shared data
} finally {
rwLock.writeLock().unlock();
}
}

2. StampedLock
o More lightweight and optimized compared to ReadWriteLock.
o Provides read, write, and optimistic read locks for better performance in read-
heavy scenarios.
3. Semaphore
o Limits access to a resource to a fixed number of threads.

java
Copy code
Semaphore semaphore = new Semaphore(3); // 3 permits

public void accessResource() {


try {
semaphore.acquire();
// Access the resource
} finally {
semaphore.release();
}
}

4. CountDownLatch
o Blocks threads until a certain number of signals or events occur.
5. CyclicBarrier
o Allows multiple threads to wait at a barrier point before all threads proceed.
When to Use Which Lock

 synchronized: Simple use cases with basic thread safety requirements.


 ReentrantLock: Advanced use cases requiring features like try-locking, interruptible
locks, or fairness.
 ReadWriteLock: When read operations are more frequent than writes.
 StampedLock: Performance-critical applications with heavy read operations.
 Semaphore: Limiting the number of threads accessing a resource.

By understanding and using locks effectively, you can create thread-safe and efficient concurrent
applications in Java.

You might also like