Lehane
Lehane

Reputation: 48678

How expensive is Java Locking?

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?

Upvotes: 1

Views: 638

Answers (2)

Bombe
Bombe

Reputation: 83850

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.

Upvotes: 4

Joachim Sauer
Joachim Sauer

Reputation: 308041

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.

Upvotes: 11

Related Questions