views:

153

answers:

2

In general, how expensive is locking in Java?

Specifically in my case: I have a multi-threaded app in which there is one main loop that takes objects off a DelayQueue and processes them (using poll()). At some point a different thread will have to remove errant elements from the queue (using remove()).

Given that the remove() is relatively uncommon, I am worried that locking on each poll() will result in slow code. Are my worries justified?

+10  A: 

They are not justified unless you profile your app and find that this is a bottleneck.

Generally speaking uncontested locking (i.e. locks that don't have to wait for someone to release it most of the time) have become a lot cheaper with some changes in Java 5 and Java 6.

Implement it safe and simple and profile if it's fast enough.

Joachim Sauer
+4  A: 

Have you taken some measurements and found that locking is too slow? No? Then it isn’t.

Honestly, though: too many people worry about too many irrelevant things. Get your code working before you worry about things like whether “++i” is faster than “i++” or similar stuff.

Bombe