2. ReadWrite Locks
In this demonstration, we interact with a shared variable, counter, that is accessed concurrently by multiple threads. Specifically, we spawn 2 writer threads that increment the counter in a loop and 8 reader threads that continuously read its value. The program is designed to terminate once the counter reaches the TARGET_VALUE.
Key principles to note in this scenario include:
- Multiple threads can simultaneously read the value of the counter without blocking each other.
- A writer thread is restricted from updating the counter's value if either another writer is already performing an update, or if any readers are currently accessing the value.
- Similarly, a reader thread is prevented from accessing the counter if a writer thread is updating its value.
This example showcases the utility of a Reader-Writer lock, which allows multiple threads to read the counter concurrently without significant blocking. This concurrent read capability ensures better performance compared to a scenario where a standard mutex might be used, leading to slower execution due to more restrictive access control.
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class Solution {
private static volatile int counter = 0;
private static final int TARGET_VALUE = 1000;
private static final ReentrantReadWriteLock lock =
new ReentrantReadWriteLock();
public static int incrementValue() {
lock.writeLock().lock();
try {
Thread.sleep(1);
if (counter < TARGET_VALUE) {
counter++;
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.writeLock().unlock();
}
return counter;
}
public static int readValue() {
lock.readLock().lock();
try {
Thread.sleep(1);
return counter;
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.readLock().unlock();
}
return 0;
}
public static void main(String[] args) {
long start = System.currentTimeMillis();
List<Thread> readers = new ArrayList<>();
for (int i = 0; i < 8; i++) {
readers.add(
new Thread(() -> {
while (readValue() < TARGET_VALUE) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
})
);
}
List<Thread> writers = new ArrayList<>();
for (int i = 0; i < 2; i++) {
writers.add(
new Thread(() -> {
while (incrementValue() < TARGET_VALUE) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
})
);
}
readers.forEach(Thread::start);
writers.forEach(Thread::start);
readers.forEach(t -> {
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
writers.forEach(t -> {
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
long end = System.currentTimeMillis();
System.out.println("Time taken: " + (end - start) / 1000.0 + " seconds");
}
}
Experiment Idea: How about modifying readValue() to use a write-lock for incrementing the counter? Observe the changes in performance, especially in terms of the Time taken. Will this alteration speed up the process or slow it down? Experiment and discover the impact!
🤖 Don't fully get this? Learn it with Claude
Stuck on 2. ReadWrite Locks? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Build the mental picture, not memorization.
I just read a lesson on **2. ReadWrite Locks** (Concurrency) and want to truly understand it. Explain 2. ReadWrite Locks from first principles using ONE vivid real-world analogy and a visual mental model — draw it as ASCII art or a clear step-by-step diagram — with a concrete example using real numbers. Then ask me one question to check I got the mental picture, and wait for my reply. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Socratic — adapts to where you're stuck.
Teach me **2. ReadWrite Locks** interactively. Ask me ONE guiding question at a time, wait for my answer, and adapt to my confusion — build the idea with me step by step instead of explaining it all at once. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Active recall exposes what you missed.
Quiz me on **2. ReadWrite Locks** with 5 questions, easy to tricky, ONE at a time. Tell me if each answer is right; at the end, explain clearly what I got wrong and why. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Intuition + hook + flashcards for long-term memory.
Help me remember **2. ReadWrite Locks** for the long term: give the one-sentence intuition, a memorable hook/mnemonic, a tiny worked example, and 3 active-recall flashcards (Q -> A). If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.