Does synchronization in a thread-safe object block other calls that can manipulate it?

Suppose I create an object protected by a stream:

PriorityBlockingQueue<Object> safeQueue = new PriorityBlockingQueue<Object>();

If I sync on it:

synchronized (safeQueue) {
   ....
}

Is there any code that blocks:

// some non-synchronized block
Object value = safeQueue.poll();
+3
source share
3 answers

No. The only time you get a lock is that another thread is also executing synchronizedon the same object. If your code synchronized (safeQueue), then the call PriorityBlockingQueue.poll()will be blocked only if it poll()was a method synchronizedor if the code used the synchronized (this)code.

When you call safeQueue.poll(), the code PriorityBlockingQueueactually uses internal ReentrantLockand does not execute synchronized (this). Here is the code for poll():

public E poll() {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        return q.poll();
    } finally {
        lock.unlock();
    }
}

, , PriorityBlockingQueue , , . , .

+4

: , , .

, ( ...) , ( ).

, , , , java.util.concurrent (, , ). , synchronized(this) (, , synchronized ), , . , Collections.synchronizedMap, ( ).

+2

, , . :

MyClass c = new MyClass();
synchronized(c) {
    ...
}

MyClass:

class MyClass {

    // foo needs a lock on this
    public synchronized void foo() { 
       ...
    }
}

c.foo(); synchronized - , , .

For example, the old Java Vectorclass was synchronized this way, so locking the object from the outside can interfere with internal locking.

0
source

All Articles