I have a requirement in Java where let’s say I have multiple bankAccountId’s and there could be multiple threads working on each bankAccountId at a time. I have to make sure that only one thread should act on a bankAccountId at a time but at the same time other threads can work on different bankAccountId. I am currently using executor service to run a fixed amount of thread pool.
I tried using semaphore and thread group but there doesn’t seems to be a direct way of assigning thread groups to executor service
The obvious way to do that would be to have threads
synchronizedon some lock object that is associated with an account whenever they are doing something to the account that should only be allowed by one thread at a time.That's classic. You don't often see
Semaphoreused for mutual exclusion today—we normally use something called "mutex" orLock—but once upon a time, it was quite common. Typically one would use a binary semaphore for that purpose. That is, aSemaphorewhoseavailablePermitsis only ever allowed to be1or0.Q: You say you "tried." Perhaps you could update your answer to say what happened when you tried, and why it wasn't satisfactory.
The rest of this probably won't help you solve your problem, but since you asked...
It's unclear to me how
ThreadGroupwould be of any help.ThreadGrouphas a lot of deprecated methods these days. Probably the most useful of the methods that are left is the one that allows your program tointerruptall of the threads in the group with a single method call.A
ThreadPoolExecutoruses aThreadFactoryto create its worker threads, and you can provide your ownThreadFactoryinstance when you construct the executor. Your thread factory can assign the new threads to whateverThreadGroup, set their priorities, or do whatever else you want to do to them before it hands them over to the executor service.