Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

You can use Concurrent Locks from the standard library. And it has been communicated that you should not be using low level concurrency constructs for years.

But people just… don’t.



> And it has been communicated that you should not be using low level concurrency constructs for years.

Where has this been communicated? The first I heard that you shouldn't use synchronized statements or blocks was in these virtual threads discussions; and the popular IDE I use for Java at work doesn't flag synchronized methods or blocks as something to be avoided. The only thing I had heard about it was that you should avoid synchronizing on objects exposed to users of your library, since it would make it possible for code outside your control to also synchronize on that same object (but IMO synchronizing on arbitrary objects you got from somewhere is itself a bad practice, you should only synchronize on objects you control). And obviously, synchronized methods or blocks do not have the "fair" mode, which might be necessary (or good) in some cases.

(And before Java 9, stack overflows within the implementation of some concurrency constructs could lead to unexpected behavior, see https://openjdk.org/jeps/270 for details; this was never a problem with synchronized methods or blocks.)


I started Java over a decade ago and by then no one was writing synchronized blocks when doing multithreaded code.


I've been coding in Java for a bit longer than that, and in my memory it's always been known that ReentrantLock is _faster_, but synchronized has better language level support (as in, the language won't let you forget to unlock, whereas with locks you need to remember your finally statement). And then, unlike ReentrantLock, synchronized uses no extra memory, which is good for things that end up being uncontended, and then in both cases, the performance doesn't matter if the lock is uncontended, which most of mine were.

There of course are things like ErrorProne that statically check that you unlocked your lock, but there's still bugs possible.


I hope anyone who learned the horrible construction of double-checked locking would have used an alternative.


You’re being downvoted, but I haven’t done Java programming in over twenty years and even I knew that!




Consider applying for YC's Winter 2027 batch! Applications are open till November 2.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: