Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For a library catalog shared by many threads, protect lookups with a read lock and inventory changes with a write lock. Java’s ReadWriteLock contract allows multiple readers at once when no writer holds the lock, while a writer gets exclusive access. That gives you a useful safety rule for the design—not a guarantee that the whole application is correct or faster.

What the library problem is asking you to protect

Imagine a catalog whose shared state is a map keyed by book ID. Threads may search for a book or list entries, while other threads add, remove, or update inventory. The concurrency problem is to let independent inspections proceed together without letting a reader observe a partially applied change or allowing overlapping writes to corrupt the state.

State the safety contract explicitly: more than one thread may hold the read lock at the same time only while the write lock is not held; a thread holding the write lock excludes both other writers and readers. A successful read-lock acquisition also observes updates made before a previous write-lock release, as specified by Java’s ReadWriteLock API documentation.

Define the lock boundaries and invariants

Use one lock consistently for every access to the mutable shared inventory. A read operation holds the read lock for the entire time it inspects the state; an operation that changes the inventory holds the write lock for the entire mutation. Do not return a mutable internal collection and then let callers use it after the lock has been released. Return an immutable copy or provide a separately synchronized interface instead.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
  • Read invariant: a lookup or enumeration does not mutate the protected state and holds the read lock throughout inspection.
  • Write invariant: every add, remove, or update holds the exclusive write lock for the full change.
  • Encapsulation invariant: callers cannot mutate protected internals outside these lock boundaries.

These boundaries protect the shared data, but they do not automatically make other application state, external side effects, or business rules thread-safe. Keep the critical section focused and include every relevant shared-state access in the same synchronization design.

Implement the catalog with ReentrantReadWriteLock

The following sketch protects a map and returns a snapshot rather than exposing its mutable contents. It omits catalog-specific validation and exception policy; those should be added without moving state access outside the lock.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

final class LibraryCatalog {
    private final Map<String, Integer> copiesByBookId = new HashMap<>();
    private final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
    private final Lock readLock = rwLock.readLock();
    private final Lock writeLock = rwLock.writeLock();

    Integer findCopies(String bookId) {
        readLock.lock();
        try {
            return copiesByBookId.get(bookId);
        } finally {
            readLock.unlock();
        }
    }

    Map<String, Integer> snapshot() {
        readLock.lock();
        try {
            return Map.copyOf(copiesByBookId);
        } finally {
            readLock.unlock();
        }
    }

    void setCopies(String bookId, int copies) {
        writeLock.lock();
        try {
            copiesByBookId.put(bookId, copies);
        } finally {
            writeLock.unlock();
        }
    }

    void removeBook(String bookId) {
        writeLock.lock();
        try {
            copiesByBookId.remove(bookId);
        } finally {
            writeLock.unlock();
        }
    }
}

Acquiring and releasing in try/finally ensures the lock is released if the operation exits exceptionally. The example’s use of Map.copyOf requires a Java version that provides that method; for an older target JDK, use an appropriate defensive-copy approach and make the returned copy unmodifiable if callers must not edit it.

Choose a fairness policy deliberately

ReentrantReadWriteLock is nonfair by default. The Java SE 18 class documentation says that under continuous contention a nonfair lock may indefinitely postpone a reader or writer, although it will normally have higher throughput than fair mode.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Fair mode uses an approximately arrival-order policy, not a strict FIFO promise for every operation. A longest-waiting writer can be granted the write lock; a group of readers may be granted the read lock when they have waited longer than all waiting writers. The untimed tryLock methods do not honor the fairness setting. Choose fairness when limiting long delays matters more than maximizing potential throughput, and treat it as a policy tradeoff rather than a starvation-proof guarantee.

Avoid read-to-write upgrade deadlock

A thread holding the read lock cannot successfully acquire the write lock while retaining its read lock. If several readers all try to upgrade, each can wait for the others to release their reads, and none can proceed. The class documentation describes the supported direction as write-to-read downgrading, not read-to-write upgrading.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

If a check performed under a read lock finds that a cached or catalog value needs updating, release the read lock first, acquire the write lock, then check the condition again before changing state. The second check is essential: another thread could have fixed or changed the state in the gap.

  1. Acquire the read lock and inspect the condition.
  2. If a write is needed, release the read lock.
  3. Acquire the write lock and recheck the condition.
  4. Perform the update only if the rechecked condition still requires it, then release the write lock.

To downgrade safely, a writer may acquire the read lock while still holding the write lock, then release the write lock. This leaves the thread with read access without opening a gap in which another writer could intervene. Oracle’s Java SE 18 examples show both the recheck pattern for cache validity and the write-to-read downgrade approach.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Decide whether a read-write lock fits the workload

A read-write lock is a workload-dependent optimization. Oracle’s Java SE 8 interface documentation says suitability depends on read frequency versus modification frequency, operation duration, contention, and multiprocessor access patterns. Very short reads can be outweighed by lock overhead; frequent writes reduce the opportunity for concurrent readers. A simple mutual-exclusion lock may be easier to reason about and perform as well or better in those cases.

Assess the choice against the actual application rather than assuming that a catalog is read-heavy:

  • Read-to-write mix: Are reads meaningfully more frequent than modifications?
  • Critical-section duration: Do read operations take long enough for concurrent readers to matter, or are they just brief map lookups?
  • Contention and hardware: Are enough threads competing, and can the runtime execute useful read work in parallel?
  • Delay requirements: Is potential reader or writer postponement acceptable, or is fair-mode behavior worth its tradeoff?
  • Complexity: Can the team reliably maintain lock boundaries and avoid holding a lock during slow unrelated work?

Start with the simplest correct synchronization, then profile and measure the representative workload. Oracle’s API puts it plainly: “Ultimately, only profiling and measurement will establish whether the use of a read-write lock is suitable for your application.” Do not claim a speedup without measurements for the workload being discussed.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.