What could be causing lock / unlock in PriorityBlockingQueue?

I read the source code of PriorityBlockingQueue in Java and I was wondering:

  • why does the tryGrow () method release the lock obtained during the offer () method, just to make its thing non-blocking and then lock again when it is ready to replace the contents of the queue? I mean, he could just keep the castle he had ...
  • How it works? Does a growing queue that includes a copy of the array not cause abnormal behavior in parallel additions, where additional additions can fully occur when the current addition increases the size of the queue?
+4
source share
1 answer

Because memory allocation can be relatively slow and can be done when the array is unlocked.

By releasing the lock, it allows other threads to continue working while it allocates a (potentially large) new array.

How this process can be done without blocking is a good practice. You should only hold the lock for a minimum period of time.

Sufficient checks are performed to ensure that no other thread will do this at the same time.

UNSAFE.compareAndSwapInt(this, allocationSpinLockOffset, 0, 1)

will only allow one thread to this section of code at a time.

pay attention to

lock.lock();
if (newArray != null && queue == array) {

, , , , , . , , , , - .

, .

Kamil .

- , , "".

+3

Source: https://habr.com/ru/post/1665009/


All Articles