0

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

2 Answers2

1

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.

Solomon Slow
  • 25,130
  • 5
  • 37
  • 57
0

The scenario seems similar as mentioned in other question

Multiple threads can work in parallel without stepping on other thread’s bankAccountId

Sagar
  • 104
  • 1
  • 5