lovespring
lovespring

Reputation: 19589

About java critical section and lock, lock on object/data or lock on code?

 synchronized(foo){
   //code
 }

suppose another thread that use another code block to access this foo object. then what happen?

if the lock is on foo object, then even the code not in this critical section, cannot access the foo object.

if the lock is on this block of code, then just two thread cannot run this block of code concurrently. but the foo object can still be accessed by using another code of block.

lock on object or lock on code, what is the true ?

Upvotes: 0

Views: 477

Answers (3)

JB Nizet
JB Nizet

Reputation: 692181

Synchronizing on an object doesn't prevent any thread to access this object. It prevents other thread to execute any block of code which is also synchronized on the same object.

So if you have

public class Foo {
}

public class SharedState
    private final Foo foo = new Foo();

    private long value;

    public void increment() {
        synchronized (foo) {
            value++;
        }
    }

    public long getValue() {
        synchronized (foo) {
            return value;
        }
    }
}

Then if one thread is currently incrementing or getting the value, no other thread won't be able to increment or read the value at the same time.

If you add a method

public Foo getFoo() {
    return foo;
}

to the SharedState, any thread will be able to call it, and to call any method of foo concurrently.

Upvotes: 3

Warren Dew
Warren Dew

Reputation: 8938

It's a lock on the object's monitor. It prevents concurrent execution by another thread of this block of code, and also of any other block of code that also requires a lock on the object's monitor. However, it does not prevent access to the object from threads executing code that does not require a lock on the object's monitor.

Upvotes: 1

Erwin Bolwidt
Erwin Bolwidt

Reputation: 31299

The statement synchronized(foo) synchronizes on the object referenced by foo.

It does not lock foo, but it locks the monitor of foo. Other threads that access object foo can do so without problems, if they don't synchronize.

But there can only be one thread at a time inside a synchronized block that synchronizes on the object pointed to be foo.

So you have to be careful that the variables in which a race condition might occur are only accessed when protected by a lock on the monitor of foo.

(But there are still many problems that can occur even if you synchronize)

Upvotes: 1

Related Questions