I got a question in an Interview asking as below:-
In Java, an object having a field, as given below...
public class MyObject
{
int count=0;
public synchronized void m()
{
for(int j=0; j< 1000; j++)
{
System.out.println(Thread.currentThread().getName()+"-> "+j);
count++;
}
System.out.println(Thread.currentThread().getName()+" completed ->"+count);
}
}
Here, the field "count" is accessed in a synchronized method, and the field is not declared volatile.
What will be the actual behavior if a Thread t1 accessing the method m() which is synchronized and using field "count" within it, and simultaneously another Thread t2 tries to access the field "count" directly ?