brain storm
brain storm

Reputation: 31252

Does synchronizing method prevents objects fields being updated?

Consider the following class.

public class Counter{

  private Lock lock = new Lock();
  private int count = 0;

  public int inc(){
    lock.lock();
    int newCount = ++count;
    lock.unlock();
    return newCount;
  }

  public int incBy2() {
      syncronized(this){
      count+=2;
      return count;   
      }
}

Now Thread T1 calls inc() method and T2 calls incBy2(). Is there a race condition here? or will T2 lock this, thereby preventing inc method to call to lock.lock()?

Upvotes: 1

Views: 46

Answers (2)

Nathan Hughes
Nathan Hughes

Reputation: 96385

The monitor on an object doesn't have any effect on the rest of the object. Acquiring the monitor on an object doesn't do anything to stop any threads from modifying fields of that object. Acquiring a lock only prevents other threads from acquiring that lock.

When you write

class Foo {

    public void doSomething() { 
        synchronized(this) {
            ...
        }
    }
}

you are better off writing

class Foo {
    private Object lock = new Object();

    public void doSomething() {
        sychronized(lock) {
            ...
        }
    }
}

The first version doesn't do anything more for you than the second one. The only difference between these two versions is that in the second one it doesn't affect the locking on doSomething if other objects acquire the monitor on the Foo object itself (so the lock is encapsulated within the object and can only be acquired by threads calling the doSomething method).

Upvotes: 1

John Vint
John Vint

Reputation: 40256

There is a race condition. You are essentially synchronizing on two separate objects. Both threads can enter inc() and incBy2() critical sections at the same time.

Upvotes: 1

Related Questions