Hacker News new | ask | show | jobs
by tombert 90 days ago
I think that the `sychronized` keyword in Java was a mistake.

I've seen classes that are meant to be used by multiple threads where literally every method has `synchronized` because "that was the only way they could get it to work". Of course, if literally every method is synchronized it literally can't actually be used by multiple threads, it just looks like it is.

Generally speaking I work pretty hard to avoid any kind of locks. Locks can be an anti-pattern in my mind: for a lot of problems, if I am reaching for a lock, it's because I haven't actually thought through the problems well enough. They're a bandaid and they create potential choke-points in the app. I also think that they're a crappy fix to try and shoehorn non-concurrent patterns into a concurrent landscape.

I personally think that making something thread-safe and concurrent while also being maintainable and fast is a hard problem, and I think lazily trying to add threads into concurrent applications is a good way to write terrible code that is impossible to debug.

Obviously no accounting for taste, but when I write programs now, I kind of always make them concurrent-first (generally using and/or reinventing the actor model). I try and build my initial algorithm to accept that concurrency is inevitable and start that from the get go. I can't remember the last time I reached for `synchronized`, though every now and then I do have to reach for ReentrantLock, and I always feel dirty doing so.

1 comments

A huge mistake, I've seen a lot of code where clearly the author thought that just adding "synchronized" would have solved any concurrency issue. And no one even talks about how synchronized is implemented, basically a monitor on the object.

The point of view is usually also wrong, they focus on the method call flow while they should think about protecting access to shared data.

Yeah. The more I learn about concurrency (which I think is a fair amount at this point), the more I respect Erlang. It was so ahead of its time with this stuff.

As I said, I feel like when I reach for a lock, about 95% of the time it’s because I don’t really understand the problem well enough.