Java Code Examples for java.util.concurrent.locks.LockSupport#park()

The following examples show how to use java.util.concurrent.locks.LockSupport#park() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CompactConcurrentHashSet2.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Possibly blocks awaiting root lock.
 */
private final void contendedLock() {
    boolean waiting = false;
    for (int s;;) {
        if (((s = lockState) & ~WAITER) == 0) {
            if (U.compareAndSwapInt(this, LOCKSTATE, s, WRITER)) {
                if (waiting)
                    waiter = null;
                return;
            }
        }
        else if ((s & WAITER) == 0) {
            if (U.compareAndSwapInt(this, LOCKSTATE, s, s | WAITER)) {
                waiting = true;
                waiter = Thread.currentThread();
            }
        }
        else if (waiting)
            LockSupport.park(this);
    }
}
 
Example 2
Source File: FIFOMutex.java    From PoseidonX with Apache License 2.0 6 votes vote down vote up
/**
 * < 锁定>
 */
public void lock()
{
    boolean wasInterrupted = false;
    Thread current = Thread.currentThread();
    waiters.add(current);
    
    // Block while not first in queue or cannot acquire lock
    while (waiters.peek() != current || !locked.compareAndSet(false, true))
    {
        LockSupport.park(this);
        if (Thread.interrupted())
        {
            wasInterrupted = true;
        }
    }
    
    waiters.remove();
    if (wasInterrupted)
    {
        current.interrupt();
    }
}
 
Example 3
Source File: ConnectablePayloadWriter.java    From servicetalk with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private Subscriber<? super T> waitForSubscriberSlowPath() throws IOException {
    writerThread = Thread.currentThread();
    for (;;) {
        final Object currState = state;
        if (currState instanceof Subscriber) {
            writerThread = null;
            return (Subscriber<? super T>) currState;
        } else if (currState == State.TERMINATED || currState == State.TERMINATING) {
            // If the subscriber is not handed off the the writer thread then the writer thread is not responsible
            // for delivering the terminal event to the Subscriber (because it never has a reference to it), and
            // the thread processing the subscribe(..) call will terminate the Subscriber instead of handing it off.
            writerThread = null;
            throw new IOException("Already closed " + closed);
        } else if (stateUpdater.compareAndSet(this, currState, State.WAITING_FOR_CONNECTED)) {
            LockSupport.park();
        }
    }
}
 
Example 4
Source File: ConnectablePayloadWriter.java    From servicetalk with Apache License 2.0 6 votes vote down vote up
private void waitForRequestNDemand() throws IOException {
    writerThread = Thread.currentThread();
    final long oldRequested = requestedUpdater.getAndSet(this, REQUESTN_ABOUT_TO_PARK);
    if (oldRequested == 0) {
        for (;;) {
            LockSupport.park();
            final long requested = this.requested;
            if (requested > 0) {
                if (requestedUpdater.compareAndSet(this, requested, requested - 1)) {
                    writerThread = null;
                    break;
                }
            } else if (requested != REQUESTN_ABOUT_TO_PARK) {
                writerThread = null;
                processClosed();
            }
        }
    } else if (oldRequested > 0) {
        writerThread = null;
        waitForRequestNDemandAvoidPark(oldRequested);
    } else {
        writerThread = null;
        processClosed();
    }
}
 
Example 5
Source File: SubmissionPublisher.java    From streamsupport with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Blocks until closed, space available or timeout.
 * For ManagedBlocker.
 */
public final boolean block() {
    long nanos = timeout;
    boolean timed = (nanos < Long.MAX_VALUE);
    long deadline = timed ? System.nanoTime() + nanos : 0L;
    while (!isReleasable()) {
        if (Thread.interrupted()) {
            timeout = INTERRUPTED;
            if (timed)
                break;
        }
        else if (timed && (nanos = deadline - System.nanoTime()) <= 0L)
            break;
        else if (waiter == null)
            waiter = Thread.currentThread();
        else if (waiting == 0)
            waiting = 1;
        else if (timed)
            LockSupport.parkNanos(this, nanos);
        else
            LockSupport.park(this);
    }
    waiter = null;
    waiting = 0;
    return true;
}
 
Example 6
Source File: Test03.java    From jdk-source-analysis with Apache License 2.0 5 votes vote down vote up
@Test
public void testServer() throws InterruptedException {
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childOption(ChannelOption.TCP_NODELAY, true)
                .childAttr(AttributeKey.newInstance("childAttr"), null)
                .handler(new ServerHandler())
                .childHandler(new ChannelInitializer<>() {
                    @Override
                    protected void initChannel(Channel ch) throws Exception {

                    }
                });
        ChannelFuture f = b.bind(PORT).sync();
        f.addListener(future -> {
            if (future.isSuccess()) {
                System.out.println(LocalDateTime.now() + ": 端口[" + PORT + "]绑定成功!");
            } else {
                System.out.println(LocalDateTime.now() + ": 端口[" + PORT + "]绑定失败!");
            }
        });
        f.channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
    LockSupport.park();
}
 
Example 7
Source File: SynchronousQueue.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Spins/blocks until node s is fulfilled.
 *
 * @param s the waiting node
 * @param e the comparison value for checking match
 * @param timed true if timed wait
 * @param nanos timeout value
 * @return matched item, or s if cancelled
 */
Object awaitFulfill(QNode s, E e, boolean timed, long nanos) {
    /* Same idea as TransferStack.awaitFulfill */
    final long deadline = timed ? System.nanoTime() + nanos : 0L;
    Thread w = Thread.currentThread();
    int spins = (head.next == s)
        ? (timed ? MAX_TIMED_SPINS : MAX_UNTIMED_SPINS)
        : 0;
    for (;;) {
        if (w.isInterrupted())
            s.tryCancel(e);
        Object x = s.item;
        if (x != e)
            return x;
        if (timed) {
            nanos = deadline - System.nanoTime();
            if (nanos <= 0L) {
                s.tryCancel(e);
                continue;
            }
        }
        if (spins > 0) {
            --spins;
            Thread.onSpinWait();
        }
        else if (s.waiter == null)
            s.waiter = w;
        else if (!timed)
            LockSupport.park(this);
        else if (nanos > SPIN_FOR_TIMEOUT_THRESHOLD)
            LockSupport.parkNanos(this, nanos);
    }
}
 
Example 8
Source File: TestLockSupport.java    From game-executor with Apache License 2.0 5 votes vote down vote up
public static void  test(){
        System.out.println("unpark startup");
        LockSupport.unpark(Thread.currentThread());
//        LockSupport.unpark(Thread.currentThread());
        System.out.println("park1");
        LockSupport.park();

//        System.out.println("park2");
//        LockSupport.park();
        System.out.println("running");

    }
 
Example 9
Source File: Phaser.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public boolean block() {
    while (!isReleasable()) {
        if (timed)
            LockSupport.parkNanos(this, nanos);
        else
            LockSupport.park(this);
    }
    return true;
}
 
Example 10
Source File: FutureTask.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
/**
 * Awaits completion or aborts on interrupt or timeout.
 *
 * @param timed true if use timed waits
 * @param nanos time to wait, if timed
 * @return state upon completion
 */
private int awaitDone(boolean timed, long nanos)
    throws InterruptedException {
    final long deadline = timed ? System.nanoTime() + nanos : 0L;
    WaitNode q = null;
    boolean queued = false;
    for (;;) {
        if (Thread.interrupted()) {
            removeWaiter(q);
            throw new InterruptedException();
        }

        int s = state;
        if (s > COMPLETING) {
            if (q != null)
                q.thread = null;
            return s;
        }
        else if (s == COMPLETING) // cannot time out yet
            Thread.yield();
        else if (q == null)
            q = new WaitNode();
        else if (!queued)
            queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
                                                 q.next = waiters, q);
        else if (timed) {
            nanos = deadline - System.nanoTime();
            if (nanos <= 0L) {
                removeWaiter(q);
                return state;
            }
            LockSupport.parkNanos(this, nanos);
        }
        else
            LockSupport.park(this);
    }
}
 
Example 11
Source File: CompletableFuture.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public boolean block() {
    if (isReleasable())
        return true;
    else if (deadline == 0L)
        LockSupport.park(this);
    else if (nanos > 0L)
        LockSupport.parkNanos(this, nanos);
    return isReleasable();
}
 
Example 12
Source File: SynchronousQueue.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Spins/blocks until node s is fulfilled.
 *
 * @param s the waiting node
 * @param e the comparison value for checking match
 * @param timed true if timed wait
 * @param nanos timeout value
 * @return matched item, or s if cancelled
 */
Object awaitFulfill(QNode s, E e, boolean timed, long nanos) {
    /* Same idea as TransferStack.awaitFulfill */
    final long deadline = timed ? System.nanoTime() + nanos : 0L;
    Thread w = Thread.currentThread();
    int spins = (head.next == s)
        ? (timed ? MAX_TIMED_SPINS : MAX_UNTIMED_SPINS)
        : 0;
    for (;;) {
        if (w.isInterrupted())
            s.tryCancel(e);
        Object x = s.item;
        if (x != e)
            return x;
        if (timed) {
            nanos = deadline - System.nanoTime();
            if (nanos <= 0L) {
                s.tryCancel(e);
                continue;
            }
        }
        if (spins > 0)
            --spins;
        else if (s.waiter == null)
            s.waiter = w;
        else if (!timed)
            LockSupport.park(this);
        else if (nanos > SPIN_FOR_TIMEOUT_THRESHOLD)
            LockSupport.parkNanos(this, nanos);
    }
}
 
Example 13
Source File: Phaser.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public boolean block() {
    if (isReleasable())
        return true;
    else if (!timed)
        LockSupport.park(this);
    else if (nanos > 0L)
        LockSupport.parkNanos(this, nanos);
    return isReleasable();
}
 
Example 14
Source File: RpcServerApp.java    From netty-learning with Apache License 2.0 5 votes vote down vote up
public void run() {

        NettyRpcServer server = new NettyRpcServer();
        server.start(address);

        //服务器启动完毕
        System.out.println("************服务器启动完成***********");

        LockSupport.park();

        //服务器关闭
        server.shutdown();
        System.out.println("************服务器关闭***********");
    }
 
Example 15
Source File: ThreadTest.java    From jdk-source-analysis with Apache License 2.0 5 votes vote down vote up
@Test
public void testInterruptNoAction() {
    // 虽然给线程发出了中断信号,但程序中并没有响应中断信号的逻辑,所以程序不会有任何反应。
    Thread thread = new Thread(() -> {
        while (true) {
            Thread.yield();
        }
    });
    thread.start();
    thread.interrupt();
    LockSupport.park();
}
 
Example 16
Source File: Phaser.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
public boolean block() {
    while (!isReleasable()) {
        if (timed)
            LockSupport.parkNanos(this, nanos);
        else
            LockSupport.park(this);
    }
    return true;
}
 
Example 17
Source File: LockSupportTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
void park() {
    LockSupport.park();
}
 
Example 18
Source File: LinkedTransferQueue.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Spins/yields/blocks until node s is matched or caller gives up.
 *
 * @param s the waiting node
 * @param pred the predecessor of s, or s itself if it has no
 * predecessor, or null if unknown (the null case does not occur
 * in any current calls but may in possible future extensions)
 * @param e the comparison value for checking match
 * @param timed if true, wait only until timeout elapses
 * @param nanos timeout in nanosecs, used only if timed is true
 * @return matched item, or e if unmatched on interrupt or timeout
 */
private E awaitMatch(Node s, Node pred, E e, boolean timed, long nanos) {
    final long deadline = timed ? System.nanoTime() + nanos : 0L;
    Thread w = Thread.currentThread();
    int spins = -1; // initialized after first item and cancel checks
    ThreadLocalRandom randomYields = null; // bound if needed

    for (;;) {
        Object item = s.item;
        if (item != e) {                  // matched
            // assert item != s;
            s.forgetContents();           // avoid garbage
            return LinkedTransferQueue.<E>cast(item);
        }
        if ((w.isInterrupted() || (timed && nanos <= 0)) &&
                s.casItem(e, s)) {        // cancel
            unsplice(pred, s);
            return e;
        }

        if (spins < 0) {                  // establish spins at/near front
            if ((spins = spinsFor(pred, s.isData)) > 0)
                randomYields = ThreadLocalRandom.current();
        }
        else if (spins > 0) {             // spin
            --spins;
            if (randomYields.nextInt(CHAINED_SPINS) == 0)
                Thread.yield();           // occasionally yield
        }
        else if (s.waiter == null) {
            s.waiter = w;                 // request unpark then recheck
        }
        else if (timed) {
            nanos = deadline - System.nanoTime();
            if (nanos > 0L)
                LockSupport.parkNanos(this, nanos);
        }
        else {
            LockSupport.park(this);
        }
    }
}
 
Example 19
Source File: SynchronousQueue.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Spins/blocks until node s is matched by a fulfill operation.
 *
 * @param s the waiting node
 * @param timed true if timed wait
 * @param nanos timeout value
 * @return matched node, or s if cancelled
 */
SNode awaitFulfill(SNode s, boolean timed, long nanos) {
    /*
     * When a node/thread is about to block, it sets its waiter
     * field and then rechecks state at least one more time
     * before actually parking, thus covering race vs
     * fulfiller noticing that waiter is non-null so should be
     * woken.
     *
     * When invoked by nodes that appear at the point of call
     * to be at the head of the stack, calls to park are
     * preceded by spins to avoid blocking when producers and
     * consumers are arriving very close in time.  This can
     * happen enough to bother only on multiprocessors.
     *
     * The order of checks for returning out of main loop
     * reflects fact that interrupts have precedence over
     * normal returns, which have precedence over
     * timeouts. (So, on timeout, one last check for match is
     * done before giving up.) Except that calls from untimed
     * SynchronousQueue.{poll/offer} don't check interrupts
     * and don't wait at all, so are trapped in transfer
     * method rather than calling awaitFulfill.
     */
    final long deadline = timed ? System.nanoTime() + nanos : 0L;
    Thread w = Thread.currentThread();
    int spins = (shouldSpin(s) ?
                 (timed ? maxTimedSpins : maxUntimedSpins) : 0);
    for (;;) {
        if (w.isInterrupted())
            s.tryCancel();
        SNode m = s.match;
        if (m != null)
            return m;
        if (timed) {
            nanos = deadline - System.nanoTime();
            if (nanos <= 0L) {
                s.tryCancel();
                continue;
            }
        }
        if (spins > 0)
            spins = shouldSpin(s) ? (spins-1) : 0;
        else if (s.waiter == null)
            s.waiter = w; // establish waiter so can park next iter
        else if (!timed)
            LockSupport.park(this);
        else if (nanos > spinForTimeoutThreshold)
            LockSupport.parkNanos(this, nanos);
    }
}
 
Example 20
Source File: SynchronousQueue.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Spins/blocks until node s is matched by a fulfill operation.
 *
 * @param s the waiting node
 * @param timed true if timed wait
 * @param nanos timeout value
 * @return matched node, or s if cancelled
 */
SNode awaitFulfill(SNode s, boolean timed, long nanos) {
    /*
     * When a node/thread is about to block, it sets its waiter
     * field and then rechecks state at least one more time
     * before actually parking, thus covering race vs
     * fulfiller noticing that waiter is non-null so should be
     * woken.
     *
     * When invoked by nodes that appear at the point of call
     * to be at the head of the stack, calls to park are
     * preceded by spins to avoid blocking when producers and
     * consumers are arriving very close in time.  This can
     * happen enough to bother only on multiprocessors.
     *
     * The order of checks for returning out of main loop
     * reflects fact that interrupts have precedence over
     * normal returns, which have precedence over
     * timeouts. (So, on timeout, one last check for match is
     * done before giving up.) Except that calls from untimed
     * SynchronousQueue.{poll/offer} don't check interrupts
     * and don't wait at all, so are trapped in transfer
     * method rather than calling awaitFulfill.
     */
    //System.err.print("[HotTub] in " + this.getClass().getName() + "#awaitFulfill with timed " + timed + " nanos " + nanos + "\n");
    //Thread.dumpStack();
    final long deadline = timed ? System.nanoTime() + nanos : 0L;
    Thread w = Thread.currentThread();
    int spins = (shouldSpin(s) ?
                 (timed ? maxTimedSpins : maxUntimedSpins) : 0);
    for (;;) {
        if (w.isInterrupted())
            s.tryCancel();
        SNode m = s.match;
        if (m != null)
            return m;
        if (timed) {
            nanos = deadline - System.nanoTime();
            if (nanos <= 0L) {
                s.tryCancel();
                continue;
            }
        }
        if (spins > 0)
            spins = shouldSpin(s) ? (spins-1) : 0;
        else if (s.waiter == null)
            s.waiter = w; // establish waiter so can park next iter
        else if (!timed)
            LockSupport.park(this);
        else if (nanos > spinForTimeoutThreshold)
            LockSupport.parkNanos(this, nanos);
    }
}