When you do work in multi-threaded environment in Java. There are lots of things you need to keep in mind to write your code correct and safe. You expect that your code will give you correct output in concurrent execution environment. But there are lots of things which could might be goes wrong in multi-threaded applications. If you want to know more about these things you can read my blog “Common problems of concurrency (Multi-Threading) in Java”. But here we are specifically talking about 64 Bit operations in multi-threaded environment. It is important to know about 64 Bit data types how they work internally, which will help us to write correct and robust code.
Whenever a thread read any variable without synchronization, it may read some stale value from variable, but at least it will read some value what any other thread write on variable, whether it is fresh or stale. This safety guarantee is known as out-of-thin-air safety. Out-of-thin-air safety applies to all variables except from 64 Bit variables (
long ). All 64 Bit variables which are not declared
volatile are unsafe to use in multiple threads. Any operation on non-atomic and non-volatile 64 Bit variable is break down in two separate 32 Bit operations by JVM. Therefore if read and write occurs in two different threads, it is possible that read of non-volatile
double return the higher 32 bits of one value and the lower 32 bits of another. Thus, even if you don’t care about stale values, it is still not safe to use shared mutable
double variables in multi-threaded programs unless they are declared volatile or guarded by a lock, because in this case it may give you totally wrong value which does not belong to program.
If you are using 64 Bit variables in your multi-threaded environment please make sure your variable must be
synchronized. In short, it is necessary to make 64 Bit variable atomic, so no other thread can interfere, if any thread is writing on 64 Bit variables. Hope this will help you to write robust code for concurrent environment in Java.