McCoy McCoy - 1 year ago 79
Java Question

Java Concurrency control multiple locks

I have a critical section, I need to control that only those threads with a given attribute value are able to enter at the same time.

For example: I have Thread#1 that handles products, Thread#2 handles products too and Thread#3 handles services


  1. T1 comes first and enters the critical section, so that the product is handled

  2. T2 wants to enter, but since there is another product being processed, it must wait

  3. T3 comes last, it is able to enter, since it needs a service (not a product) to be processed

  4. T1 goes out, now T2 is able to get in

I think it looks quite simple, but I wasn't able to find anything that fits the requirement.
My question is, how can I achieve this? any reference to any source of information about this will be appreciated

Thank you very much in advance

Answer Source

How about this:

private ConcurrentMap<Integer, Semaphore> semaphores = new ConcurrentHashMap<>();

public void enter(int id) {
    Semaphore s = semaphores.computeIfAbsent(id, f -> new Semaphore(1));

    try {
        // Critical section.
    } catch (InterruptedException e) {
        // Exception handling.
    } finally {
  • The hash map guarantees fast access and can grow dynamically. Furthermore, you're able to use objects as keys.
  • If you know the number of IDs at compile time, you can also use an unmodifiable or immutable map and prefill it.
  • The semaphore can be adjusted as well: set different numbers of permits and fairness guarantees for different IDs.
  • The wrapping class can provide additional methods, e.g. a non-blocking tryEnter(int) via Semaphore#tryAcquire().
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download