corejava6

26. Describe an ‘Atomic Action’ in context of programming.
An atomic action is one that effectively happens all at once. An atomic action cannot stop in the middle: it either happens completely, or it doesn't happen at all. No side effects of an atomic action are visible until the action is complete.
Atomic actions cannot be interleaved, so they can be used without fear of thread interference. However, this does not eliminate all need to synchronize atomic actions, because memory consistency errors are still possible.
E.g.
i) Reads and writes are atomic for reference variables and for most primitive variables (all types except double and long)                                                                                                                
ii) Reads and writes are atomic for all variables declared volatile (including long and double)            


27. What is volatile keyword? What are its uses?
The volatile keyword guarantees more than just that volatile variables are written to and read from main memory.
It cannot be used with method or class and it can only be used with a variable.
Uses:-
i) To make reading double and long atomic.
ii) To provide a memory barrier to resolve memory consistency errors so that all reader threads will always see updated values.
iii) Alternative (not replacement) to synchronization.


28. What guarantee volatile variable provides?
It guarantees ordering of code i.e. volatile assignments can prevent undesirable code re-ordering and code optimization.
It also guarantees visibility of code which ensures changes made in one thread is visible to others.
It may also guarantee atomicity of variable.


29. Can we make array volatile in Java?
Yes, you can make an array volatile in Java but only the reference which is pointing to an array, not the whole array. It means that, if one thread changes the reference variable to points to another array, that will provide a volatile guarantee, but if multiple threads are changing individual array elements they won't be having visibility guarantee provided by the volatile modifier.


30. What is the Difference between synchronized and volatile keyword in Java?
The volatile is a field modifier while synchronized modifies code blocks and methods.

 Synchronized obtains and releases the lock on monitor’s Java volatile doesn't require that.

 Synchronized keywords needs threads to be blocked for waiting for any monitoring that is not the case with the volatile.

 Synchronized method affects performance more than a volatile keyword.

 Synchronized keyword is likely to have more overhead than volatile. Because volatile keyword only synchronizes the value of one variable between Thread memory and "main" memory while synchronized synchronizes the value of all variable between thread memory and "main" memory and locks and releases a monitor to boot.

Volatile variable could be null but you cannot use synchronized on null object.


No comments:

Post a Comment