Fair and unfair synchronization queues of SynchronousQueue in java
This article is mainly about "Fair and unfair synchronization queue of SynchronousQueue in java". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn the fair and unfair synchronization queue of SynchronousQueue in java.
SynchronousQueue is divided into fair and unfair synchronization queues
Input true in the construction method, indicating that the fair queue now chooses to implement the entry and exit element FIFO through the method in TransferQueue.
Otherwise, input false and use TransferStack to implement entry and exit elements. There is no fixed order.
Node composition in TransfererStack
Static final class SNode {
Volatile SNode next
Volatile SNode match
Volatile Thread waiter
Object item
Int mode
Volatile SNode head
}
Static {
Try {
UNSAFE = sun.misc.Unsafe.getUnsafe ()
Class k = SNode.class
MatchOffset = UNSAFE.objectFieldOffset
(k.getDeclaredField ("match"))
NextOffset = UNSAFE.objectFieldOffset
(k.getDeclaredField ("next"))
} catch (Exception e) {
Throw new Error (e)
}
}
Implementation of transfer method
E transfer (E e, boolean timed, long nanos) {
/ *
* Basic algorithm is to loop trying one of three actions:
*
* 1. If apparently empty or already containing nodes of same
* mode, try to push node on stack and wait for a match
* returning it, or null if cancelled.
*
* 2. If apparently containing node of complementary mode
* try to push a fulfilling node on to stack, match
* with corresponding waiting node, pop both from
* stack, and return matched item. The matching or
* unlinking might not actually be necessary because of
* other threads performing action 3:
*
* 3. If top of stack already holds another fulfilling node
* help it out by doing its match and/or pop
* operations, and then continue. The code for helping
* is essentially the same as for fulfilling, except
* that it doesn't return the item.
, /
SNode s = null; / / constructed/reused as needed
Int mode = (e = = null)? REQUEST: DATA
For (;;) {
SNode h = head
If (h = = null | | h.mode = = mode) {/ / empty or same-mode
If (timed & & nanos