23 */
24
25 /*
26 * This file is available under and governed by the GNU General Public
27 * License version 2 only, as published by the Free Software Foundation.
28 * However, the following notice accompanied the original version of this
29 * file:
30 *
31 * Written by Doug Lea with assistance from members of JCP JSR-166
32 * Expert Group and released to the public domain, as explained at
33 * http://creativecommons.org/publicdomain/zero/1.0/
34 */
35
36 package java.util.concurrent.locks;
37
38 import java.util.ArrayList;
39 import java.util.Collection;
40 import java.util.Date;
41 import java.util.concurrent.TimeUnit;
42 import java.util.concurrent.ForkJoinPool;
43 import jdk.internal.misc.Unsafe;
44
45 /**
46 * Provides a framework for implementing blocking locks and related
47 * synchronizers (semaphores, events, etc) that rely on
48 * first-in-first-out (FIFO) wait queues. This class is designed to
49 * be a useful basis for most kinds of synchronizers that rely on a
50 * single atomic {@code int} value to represent state. Subclasses
51 * must define the protected methods that change this state, and which
52 * define what that state means in terms of this object being acquired
53 * or released. Given these, the other methods in this class carry
54 * out all queuing and blocking mechanics. Subclasses can maintain
55 * other state fields, but only the atomically updated {@code int}
56 * value manipulated using methods {@link #getState}, {@link
57 * #setState} and {@link #compareAndSetState} is tracked with respect
58 * to synchronization.
59 *
60 * <p>Subclasses should be defined as non-public internal helper
61 * classes that are used to implement the synchronization properties
62 * of their enclosing class. Class
120 * </ul>
121 *
122 * Each of these methods by default throws {@link
123 * UnsupportedOperationException}. Implementations of these methods
124 * must be internally thread-safe, and should in general be short and
125 * not block. Defining these methods is the <em>only</em> supported
126 * means of using this class. All other methods are declared
127 * {@code final} because they cannot be independently varied.
128 *
129 * <p>You may also find the inherited methods from {@link
130 * AbstractOwnableSynchronizer} useful to keep track of the thread
131 * owning an exclusive synchronizer. You are encouraged to use them
132 * -- this enables monitoring and diagnostic tools to assist users in
133 * determining which threads hold locks.
134 *
135 * <p>Even though this class is based on an internal FIFO queue, it
136 * does not automatically enforce FIFO acquisition policies. The core
137 * of exclusive synchronization takes the form:
138 *
139 * <pre>
140 * Acquire:
141 * while (!tryAcquire(arg)) {
142 * <em>enqueue thread if it is not already queued</em>;
143 * <em>possibly block current thread</em>;
144 * }
145 *
146 * Release:
147 * if (tryRelease(arg))
148 * <em>unblock the first queued thread</em>;
149 * </pre>
150 *
151 * (Shared mode is similar but may involve cascading signals.)
152 *
153 * <p id="barging">Because checks in acquire are invoked before
154 * enqueuing, a newly acquiring thread may <em>barge</em> ahead of
155 * others that are blocked and queued. However, you can, if desired,
156 * define {@code tryAcquire} and/or {@code tryAcquireShared} to
157 * disable barging by internally invoking one or more of the inspection
158 * methods, thereby providing a <em>fair</em> FIFO acquisition order.
159 * In particular, most fair synchronizers can define {@code tryAcquire}
160 * to return {@code false} if {@link #hasQueuedPredecessors} (a method
161 * specifically designed to be used by fair synchronizers) returns
162 * {@code true}. Other variations are possible.
163 *
164 * <p>Throughput and scalability are generally highest for the
165 * default barging (also known as <em>greedy</em>,
166 * <em>renouncement</em>, and <em>convoy-avoidance</em>) strategy.
1548 w = next;
1549 }
1550 }
1551 }
1552
1553 /**
1554 * Implements uninterruptible condition wait.
1555 * <ol>
1556 * <li>Save lock state returned by {@link #getState}.
1557 * <li>Invoke {@link #release} with saved state as argument,
1558 * throwing IllegalMonitorStateException if it fails.
1559 * <li>Block until signalled.
1560 * <li>Reacquire by invoking specialized version of
1561 * {@link #acquire} with saved state as argument.
1562 * </ol>
1563 */
1564 public final void awaitUninterruptibly() {
1565 ConditionNode node = new ConditionNode();
1566 int savedState = enableWait(node);
1567 LockSupport.setCurrentBlocker(this); // for back-compatibility
1568 boolean interrupted = false;
1569 while (!canReacquire(node)) {
1570 if (Thread.interrupted())
1571 interrupted = true;
1572 else if ((node.status & COND) != 0) {
1573 try {
1574 ForkJoinPool.managedBlock(node);
1575 } catch (InterruptedException ie) {
1576 interrupted = true;
1577 }
1578 } else
1579 Thread.onSpinWait(); // awoke while enqueuing
1580 }
1581 LockSupport.setCurrentBlocker(null);
1582 node.clearStatus();
1583 acquire(node, savedState, false, false, false, 0L);
1584 if (interrupted)
1585 Thread.currentThread().interrupt();
1586 }
1587
1588 /**
1589 * Implements interruptible condition wait.
1590 * <ol>
1591 * <li>If current thread is interrupted, throw InterruptedException.
1592 * <li>Save lock state returned by {@link #getState}.
1593 * <li>Invoke {@link #release} with saved state as argument,
1594 * throwing IllegalMonitorStateException if it fails.
1595 * <li>Block until signalled or interrupted.
1596 * <li>Reacquire by invoking specialized version of
1597 * {@link #acquire} with saved state as argument.
1598 * <li>If interrupted while blocked in step 4, throw InterruptedException.
1599 * </ol>
1600 */
1601 public final void await() throws InterruptedException {
1602 if (Thread.interrupted())
1603 throw new InterruptedException();
1604 ConditionNode node = new ConditionNode();
1605 int savedState = enableWait(node);
1606 LockSupport.setCurrentBlocker(this); // for back-compatibility
1607 boolean interrupted = false, cancelled = false;
1608 while (!canReacquire(node)) {
1609 if (interrupted |= Thread.interrupted()) {
1610 if (cancelled = (node.getAndUnsetStatus(COND) & COND) != 0)
1611 break; // else interrupted after signal
1612 } else if ((node.status & COND) != 0) {
1613 try {
1614 ForkJoinPool.managedBlock(node);
1615 } catch (InterruptedException ie) {
1616 interrupted = true;
1617 }
1618 } else
1619 Thread.onSpinWait(); // awoke while enqueuing
1620 }
1621 LockSupport.setCurrentBlocker(null);
1622 node.clearStatus();
1623 acquire(node, savedState, false, false, false, 0L);
1624 if (interrupted) {
1625 if (cancelled) {
1626 unlinkCancelledWaiters(node);
1627 throw new InterruptedException();
1628 }
1629 Thread.currentThread().interrupt();
1630 }
1631 }
1632
1633 /**
1634 * Implements timed condition wait.
|
23 */
24
25 /*
26 * This file is available under and governed by the GNU General Public
27 * License version 2 only, as published by the Free Software Foundation.
28 * However, the following notice accompanied the original version of this
29 * file:
30 *
31 * Written by Doug Lea with assistance from members of JCP JSR-166
32 * Expert Group and released to the public domain, as explained at
33 * http://creativecommons.org/publicdomain/zero/1.0/
34 */
35
36 package java.util.concurrent.locks;
37
38 import java.util.ArrayList;
39 import java.util.Collection;
40 import java.util.Date;
41 import java.util.concurrent.TimeUnit;
42 import java.util.concurrent.ForkJoinPool;
43 import java.util.concurrent.RejectedExecutionException;
44 import jdk.internal.misc.Unsafe;
45
46 /**
47 * Provides a framework for implementing blocking locks and related
48 * synchronizers (semaphores, events, etc) that rely on
49 * first-in-first-out (FIFO) wait queues. This class is designed to
50 * be a useful basis for most kinds of synchronizers that rely on a
51 * single atomic {@code int} value to represent state. Subclasses
52 * must define the protected methods that change this state, and which
53 * define what that state means in terms of this object being acquired
54 * or released. Given these, the other methods in this class carry
55 * out all queuing and blocking mechanics. Subclasses can maintain
56 * other state fields, but only the atomically updated {@code int}
57 * value manipulated using methods {@link #getState}, {@link
58 * #setState} and {@link #compareAndSetState} is tracked with respect
59 * to synchronization.
60 *
61 * <p>Subclasses should be defined as non-public internal helper
62 * classes that are used to implement the synchronization properties
63 * of their enclosing class. Class
121 * </ul>
122 *
123 * Each of these methods by default throws {@link
124 * UnsupportedOperationException}. Implementations of these methods
125 * must be internally thread-safe, and should in general be short and
126 * not block. Defining these methods is the <em>only</em> supported
127 * means of using this class. All other methods are declared
128 * {@code final} because they cannot be independently varied.
129 *
130 * <p>You may also find the inherited methods from {@link
131 * AbstractOwnableSynchronizer} useful to keep track of the thread
132 * owning an exclusive synchronizer. You are encouraged to use them
133 * -- this enables monitoring and diagnostic tools to assist users in
134 * determining which threads hold locks.
135 *
136 * <p>Even though this class is based on an internal FIFO queue, it
137 * does not automatically enforce FIFO acquisition policies. The core
138 * of exclusive synchronization takes the form:
139 *
140 * <pre>
141 * <em>Acquire:</em>
142 * while (!tryAcquire(arg)) {
143 * <em>enqueue thread if it is not already queued</em>;
144 * <em>possibly block current thread</em>;
145 * }
146 *
147 * <em>Release:</em>
148 * if (tryRelease(arg))
149 * <em>unblock the first queued thread</em>;
150 * </pre>
151 *
152 * (Shared mode is similar but may involve cascading signals.)
153 *
154 * <p id="barging">Because checks in acquire are invoked before
155 * enqueuing, a newly acquiring thread may <em>barge</em> ahead of
156 * others that are blocked and queued. However, you can, if desired,
157 * define {@code tryAcquire} and/or {@code tryAcquireShared} to
158 * disable barging by internally invoking one or more of the inspection
159 * methods, thereby providing a <em>fair</em> FIFO acquisition order.
160 * In particular, most fair synchronizers can define {@code tryAcquire}
161 * to return {@code false} if {@link #hasQueuedPredecessors} (a method
162 * specifically designed to be used by fair synchronizers) returns
163 * {@code true}. Other variations are possible.
164 *
165 * <p>Throughput and scalability are generally highest for the
166 * default barging (also known as <em>greedy</em>,
167 * <em>renouncement</em>, and <em>convoy-avoidance</em>) strategy.
1549 w = next;
1550 }
1551 }
1552 }
1553
1554 /**
1555 * Implements uninterruptible condition wait.
1556 * <ol>
1557 * <li>Save lock state returned by {@link #getState}.
1558 * <li>Invoke {@link #release} with saved state as argument,
1559 * throwing IllegalMonitorStateException if it fails.
1560 * <li>Block until signalled.
1561 * <li>Reacquire by invoking specialized version of
1562 * {@link #acquire} with saved state as argument.
1563 * </ol>
1564 */
1565 public final void awaitUninterruptibly() {
1566 ConditionNode node = new ConditionNode();
1567 int savedState = enableWait(node);
1568 LockSupport.setCurrentBlocker(this); // for back-compatibility
1569 boolean interrupted = false, rejected = false;
1570 while (!canReacquire(node)) {
1571 if (Thread.interrupted())
1572 interrupted = true;
1573 else if ((node.status & COND) != 0) {
1574 try {
1575 if (rejected)
1576 node.block();
1577 else
1578 ForkJoinPool.managedBlock(node);
1579 } catch (RejectedExecutionException ex) {
1580 rejected = true;
1581 } catch (InterruptedException ie) {
1582 interrupted = true;
1583 }
1584 } else
1585 Thread.onSpinWait(); // awoke while enqueuing
1586 }
1587 LockSupport.setCurrentBlocker(null);
1588 node.clearStatus();
1589 acquire(node, savedState, false, false, false, 0L);
1590 if (interrupted)
1591 Thread.currentThread().interrupt();
1592 }
1593
1594 /**
1595 * Implements interruptible condition wait.
1596 * <ol>
1597 * <li>If current thread is interrupted, throw InterruptedException.
1598 * <li>Save lock state returned by {@link #getState}.
1599 * <li>Invoke {@link #release} with saved state as argument,
1600 * throwing IllegalMonitorStateException if it fails.
1601 * <li>Block until signalled or interrupted.
1602 * <li>Reacquire by invoking specialized version of
1603 * {@link #acquire} with saved state as argument.
1604 * <li>If interrupted while blocked in step 4, throw InterruptedException.
1605 * </ol>
1606 */
1607 public final void await() throws InterruptedException {
1608 if (Thread.interrupted())
1609 throw new InterruptedException();
1610 ConditionNode node = new ConditionNode();
1611 int savedState = enableWait(node);
1612 LockSupport.setCurrentBlocker(this); // for back-compatibility
1613 boolean interrupted = false, cancelled = false, rejected = false;
1614 while (!canReacquire(node)) {
1615 if (interrupted |= Thread.interrupted()) {
1616 if (cancelled = (node.getAndUnsetStatus(COND) & COND) != 0)
1617 break; // else interrupted after signal
1618 } else if ((node.status & COND) != 0) {
1619 try {
1620 if (rejected)
1621 node.block();
1622 else
1623 ForkJoinPool.managedBlock(node);
1624 } catch (RejectedExecutionException ex) {
1625 rejected = true;
1626 } catch (InterruptedException ie) {
1627 interrupted = true;
1628 }
1629 } else
1630 Thread.onSpinWait(); // awoke while enqueuing
1631 }
1632 LockSupport.setCurrentBlocker(null);
1633 node.clearStatus();
1634 acquire(node, savedState, false, false, false, 0L);
1635 if (interrupted) {
1636 if (cancelled) {
1637 unlinkCancelledWaiters(node);
1638 throw new InterruptedException();
1639 }
1640 Thread.currentThread().interrupt();
1641 }
1642 }
1643
1644 /**
1645 * Implements timed condition wait.
|