0

Given this example class:

class Example {
    String str = "";
    public synchronized boolean foo () { str = "foo"; }
    public boolean bar() { str = "bar"; }
    public synchronized boolean baz() { str = "baz"; }
}

From this post, it is clear that any thread can call the bar method. Say thread T1 is in the middle of executing foo() and thread T2 calls bar(). Can bar() reassign str even though foo has obtained a lock? What about the same question if baz is called by T2 even though T2 is in the middle of executing foo?

Community
  • 1
  • 1
jaynp
  • 3,275
  • 4
  • 30
  • 43

3 Answers3

3

You need to make str volatile first for threads to be a able to see each others changes else they will only see local copy.

Second issue is of one thread is in middle of modifying it and another thread reads it then you will get inconsistent state. So if a variable is shared across threads then make it volatile and any modification should be made in a synchronized block/method.

So to answer your questiond : Can bar() reassign str even though foo has obtained a lock? -> Yes.

Same applies for T2. But you will not able to gurantee a consistent state unless you synchronize bar.

Lokesh
  • 7,810
  • 6
  • 48
  • 78
0

Say thread T1 is in the middle of executing foo() and thread T2 calls bar(). Can bar() reassign str even though foo has obtained a lock?

yes. Because, even though foo() is synchronized, bar() is not. Thread T1 has obtained the lock on the object of class Example and it's synchronized functions will be locked, not the non-synchronized one.

What about the same question if baz is called by T2 even though T1 is in the middle of executing foo?

This time, as baz() function is synchronized, T2 will wait if T1 has already gained access to one of the synchronized function(i.e, foo()) of the object of class Example.

Sage
  • 15,290
  • 3
  • 33
  • 38
0

synchronized does the following: if (lets say) 5 threads are asking for access, 4 are put on hold and 1 is let through. You always need to synchronize on something, because someone needs to be the monitor to check how many threads are in the line and will be let in next once the current thread is done.

But if you do not have this synchronized block, no one is restricting access. Thats like having the most critical bouncer at a club, while the back-door is widely open. Even though the "club" has synchronized access, even the best monitor (bouncer) can't stop people from using the back-door, if he doesn't know about it.

TwoThe
  • 13,879
  • 6
  • 30
  • 54