-1

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 ?

Sugyan sahu
  • 129
  • 1
  • 8

2 Answers2

1

t1 will have visibility of the most up-to-date value of count flushed to main memory, reading it when it enters the synchronized block, and writing it back when it leaves; the value it prints at the end will always be 1000 more than the value it read.

t2 will read the value of count at some time; it is allowed to keep a cached value. Any updates to the value of count may be flushed to main memory immediately, later, or never.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
-2

There will be race condition. As ONLY the method "m" is thread safe. Here you can find the detail about race condition