0

I am having an object of a class having some state. This object has two methods (method1() and method2()), both are changing the state of obj. method1() is synchronized but method2() is not synchronized.

Now two threads, thread1 and threads2 approach object ->threads1 calls method1() which is synchronized -> thread2 calls method2() which is not synchronized.

What I found with my test results is the method2() was executing correctly even though method1() holding a lock. But I thought that if a lock is acquired on the entire object by putting the synchronised keyword on method, how many another method can be executed. It should wait.

Your opinion is highly appreciated.

Vimal Panchal
  • 301
  • 1
  • 5
  • 15

3 Answers3

2

When we say that calling a synchronized method or block results in locking, all that means is that the thread acquires the lock exclusively. It does not mean that the state of the object whose lock the thread acquired receives any other protection.

(Intrinsic locks are attached to objects, including class objects, as a convenience by the language designers. That decision may not have been the best one. Using a dedicated object to lock on is usually a better idea.)

Your unsynchronized call is potentially corrupting shared state. In addition to that no memory barriers are put in place and changes made by threads calling the unsynchronized method may not be seen by other threads. The JIT will not take cross-thread visibility concerns into account when making optimizations like reordering code.

It can be difficult to predict what will happen in code that is not adequately synchronized.

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
1

But I thought that if a lock is acquired on the entire object by putting sync on method than how any other method can be executed. It should wait.

A lock has no idea what it locks. It just prevents other threads from acquiring that very same lock.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
1

Some good answers here but I thought a bit more detail was in order.

What is found with my test results that the method2() was executing happily even though method1() had a lock.

When a thread enters a synchronized method, it locks the monitor associated with the object instance. Other threads can call other non-synchronized methods on that same object instance as much as they like. The lock being held by thread1 doesn't change obj in any way. Only if thread2 also goes to lock the same object instance would it be blocked.

But I thought that if a lock is acquired on the entire object by putting sync on method than how any other method can be executed. It should wait.

No, this is not the case. There would be a big performance hit if every method call would have to see if there was a lock on the object whose method was being called.

Gray
  • 115,027
  • 24
  • 293
  • 354