http://bytes.com/topic/java/insights...ls-article-1-a
Here I will discuss a few more things
1> Which operations are atomic in Java?
Ans: Writes to volatiles, writes to references, and writes to 32 bit or smaller scalar values. While one of these operations have started by a thread to a particular variable, the thread must finish it before any other thread tries to write to the same variable. So these assignment operations may be used anywhere in the code without producing any garbage value due to intermediate thread interfarence.
2> Is a write immediately visible to another thread?
Ans: If a write operation by one thread T1 is followed by a read operation by another thread T2 it is not obvious that T2 will see the value written by T1. because T1 may read the value from it's local cache, which is an old value.
3> How to make it visible?
Ans: If the variable is volatile then T2 will always see the value written by T1.
4> Which operation may produce garbage value when accessed by more than one thread?
Ans. Writes to non-volatile 64-bit values (i.e., longs and doubles).
5> Why is synchronization required?
Ans. Say there are 4 code blocks (snipet) which we never want to be executed by more than one thread. This means that when any one of these blocks is being executed by a thread T1, then the same block or any of the other 3 blocks will not execute by any other thread T2. T2 must wait until until T1 finishes. as T1 finishes then only T2 will enter into any of these 4 blocks and execute it.
6> How is this acomplished?
Ans. This is acomplished by the word synchronized keyword.
An object of any class A need to be created as below.
Expand|Select|Wrap|Line Numbers
- A obj = new A();
Expand|Select|Wrap|Line Numbers
- synchronized(obj){
- //Code block: i.e. Lines of code follows
- }