I have to make sure that only one thread should act on a bankAccountId at a time
The obvious way to do that would be to have threads synchronized
on 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.
I tried using semaphore...
That's classic. You don't often see Semaphore
used for mutual exclusion today—we normally use something called "mutex" or Lock
—but once upon a time, it was quite common. Typically one would use a binary semaphore for that purpose. That is, a Semaphore
whose availablePermits
is only ever allowed to be 1
or 0
.
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...
...and thread group
It's unclear to me how ThreadGroup
would be of any help. ThreadGroup
has a lot of deprecated methods these days. Probably the most useful of the methods that are left is the one that allows your program to interrupt
all of the threads in the group with a single method call.
there doesn’t seems to be a direct way of assigning thread groups to executor service
A ThreadPoolExecutor
uses a ThreadFactory
to create its worker threads, and you can provide your own ThreadFactory
instance when you construct the executor. Your thread factory can assign the new threads to whatever ThreadGroup
, set their priorities, or do whatever else you want to do to them before it hands them over to the executor service.