0

My application gets lot of incoming HTTP request. In header of each request, there's a key value pair.

Say Header1=App1

The value App1 keeps on changing.

So next it can be App2,App3 and like that

. However these values can keep on coming in any order. I need to handle race condition wherein if multiple request with App1 comes, I acquire

ReentrantReadWriteLock

on App1. Simultaneously if I get request for App2, I will acquire ReentrantReadWriteLock for App2. Both the locks needs to be mutually exclusive otherwise I will have performance bottleneck wherein unless App1 logic is executed, App2 will not be executed.

What I am trying to do is if multiple request for App1 comes, then they have to wait. Simultaneously if request for App2 is received, it will be executed in parallel with current App1 request. Essentially synchronize on unique values. I am actually clueless. Appreciate guidance. P.S. I cannot use synchronized as it will lead to performance bottleneck

AngelsandDemons
  • 2,823
  • 13
  • 47
  • 70

1 Answers1

1

You can use a ConcurrentMap to map request keys to locks, for example:

ConcurrentMap<String, ReentrantLock> locks = ...

ReentrantLock lock = locks.computeIfAbsent(key, k -> new ReentrantLock());
lock.lock();
// do work
lock.unlock();
janos
  • 120,954
  • 29
  • 226
  • 236