Hacker News new | ask | show | jobs
by nullwasamistake 2587 days ago
Ironically volatile is just as bad in Java for different reasons. Frequently used for "lock free" synchronization, its usually actually worse than using locks because it can't be cached between cores. The variable is always loaded from main memory, which is usually much worse than holding a lock mutex in registers.
2 comments

The standard pattern for working with atomics in java (volatiles are of limited use without atomic field updaters or varhandles) is to read it into a local variable, operate on that and only write it back to the volatile once you're done.

That has many benefits, among them the ability to store its value in registers.

For primitives Java uses special CPU instructions. In the Atomic* package. It's not recommended for plain objects.
> Frequently used for "lock free" synchronization, its usually actually worse than using locks

If you want lock-free what do you suggest we use instead of volatile?

> which is usually much worse than holding a lock mutex in registers

How can you hold a mutex in a register? That doesn't make any sense.

You can use a lock but held in a regular CPU register. They're just regular variables for the most part.

Lock free in Java is usually worse that what the JVM can pull off with lock elison

> You can use a lock but held in a regular CPU register. They're just regular variables for the most part.

I don't understand this. If your lock variable is in a CPU register how do other CPUs acquire the lock?

> Lock free in Java is usually worse that what the JVM can pull off with lock elision

I don't understand this either. Java's lock elision is only going to make a concurrent object 'lock-free' in the case where the object does not escape the compilation unit. In which case again how would another thread use it? Java will also combine adjacent critical sections created by monitors even if they escape, but it won't make them lock-free in that case.

JVM is very smart about locking. My knowledge is limited but this is a great article. https://shipilev.net/jvm/anatomy-quarks/19-lock-elision/
I work with the JVM at Oracle and I’ve given talks about the lock elision algorithm. It doesn’t do what you think it does and what it does do is not related to lock-free like you think it is.