Reputation: 1008
I'm writing a small piece of code that will be called by many threads simultaneously to gather statistics on processes. The code is short and quick but must be somehow synchronized to keep stats correct. The typical load would be around 100-200 calls per second but can escalate to 5000 calls per second at some point during the day.
Is synchronized
to slow to handle this? If I have 16 cores as opposed to 4, does it get more expensive to handle the more cores I have?
// This method is called by multiple threads
public synchronized void record(String alias, long result, int delta) {
// compute custom stats here... (short & quick)
}
The other option I was considering is to use a Semaphore
to access the critical section. Are they faster than option #1? Do they still use locks behind the scenes?
private Semaphore s = new Semaphore(1);
public void record(String alias, long result, int delta)
throws InterruptedException {
boolean acquired = false;
try {
this.s.acquire();
acquired = true;
// compute custom stats here... (short & quick)
} finally {
if (acquired) this.s.release();
}
}
Finally, I was considering a Queue (each caller is a producer + one Executor
as consumer) but I wanted to avoid an extra thread/executor as the consumer.
Other better option?
Last but not least, for my use case of 5000 calls per second am I worrying too much? If so I would use the simplest option (synchronize the method) to control concurrency.
Upvotes: 2
Views: 1149
Reputation: 152
If your compute is short and quick, then using semaphore vs synchronized is not really going to give you a lead. For concurrent processing of messages, producer/consumer is the way to go. You can use blocking queue and then spin multiple consumer threads.
Upvotes: 1