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

The following are Jave code examples for showing how to use park() of the java.util.concurrent.locks.LockSupport class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: java-concurrency-cheatsheet   File: Main.java   View Source Code Vote up 6 votes
@Override
public void run() {
    synchronized (u) {
        System.out.printf("%s in %s\n", new Date(), getName());
        LockSupport.park(u);
        if (isInterrupted()) {
            System.out.println(getName() + " is interrupted.");
        }
    }

    // 最多阻塞 5 s
    // 如果中断位为 true,则下面的语句无效,可以对比上面如果是使用 Thread.interrupted() 方法判断有什么不同
    LockSupport.parkNanos(this, TimeUnit.SECONDS.toNanos(5));

    System.out.printf("%s %s ends\n", new Date(), getName());
}
 
Example 2
Project: reactive.loanbroker.system   File: Javaslang2CircuitBreakerTests.java   View Source Code Vote up 6 votes
@Test
public void testCircuitBreaker() {


    CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom()
            .failureRateThreshold(25)
            .waitDurationInOpenState(Duration.ofMillis(1000))
            .ringBufferSizeInHalfOpenState(1)
            .ringBufferSizeInClosedState(2)
            .build();

    CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("test");

    Observable.interval(500,TimeUnit.MILLISECONDS).map(i -> {
        if(1==1) throw new RuntimeException("BAM");
        return "result"+i;
    })
            .lift(CircuitBreakerOperator.of(circuitBreaker)).map(result -> result)
            .subscribe(System.out::println);


    LockSupport.park();

}
 
Example 3
Project: jdk8u-jdk   File: ConcurrentHashMap.java   View Source Code Vote up 6 votes
/**
 * 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 4
Project: android-retroflow   File: SubmissionPublisher.java   View Source Code Vote up 6 votes
/**
 * 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 5
Project: OpenJSharp   File: ConcurrentHashMap.java   View Source Code Vote up 6 votes
/**
 * 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 6
Project: sstable-adaptor   File: WaitQueue.java   View Source Code Vote up 5 votes
public void await() throws InterruptedException
{
    while (!isSignalled())
    {
        checkInterrupted();
        LockSupport.park();
    }
    checkAndClear();
}
 
Example 7
Project: openjdk-jdk10   File: Phaser.java   View Source Code Vote up 5 votes
public boolean block() {
    while (!isReleasable()) {
        if (timed)
            LockSupport.parkNanos(this, nanos);
        else
            LockSupport.park(this);
    }
    return true;
}
 
Example 8
Project: LearningOfThinkInJava   File: LockSupportDemo.java   View Source Code Vote up 5 votes
@Override
public void run() {
    synchronized (u){
        System.out.println("in "+getName());
        LockSupport.park();
    }
}
 
Example 9
Project: android-retroatomic   File: Phaser.java   View Source Code Vote up 5 votes
public boolean block() {
    while (!isReleasable()) {
        if (timed) {
            LockSupport.parkNanos(this, nanos);
        } else {
            LockSupport.park(this);
        }
    }
    return true;
}
 
Example 10
Project: guava-mock   File: AbstractFuture.java   View Source Code Vote up 5 votes
/**
 * {@inheritDoc}
 *
 * <p>The default {@link AbstractFuture} implementation throws {@code InterruptedException} if the
 * current thread is interrupted before or during the call, even if the value is already
 * available.
 *
 * @throws InterruptedException if the current thread was interrupted before or during the call
 *     (optional but recommended).
 * @throws CancellationException {@inheritDoc}
 */
@CanIgnoreReturnValue
@Override
public V get() throws InterruptedException, ExecutionException {
  if (Thread.interrupted()) {
    throw new InterruptedException();
  }
  Object localValue = value;
  if (localValue != null & !(localValue instanceof SetFuture)) {
    return getDoneValue(localValue);
  }
  Waiter oldHead = waiters;
  if (oldHead != Waiter.TOMBSTONE) {
    Waiter node = new Waiter();
    do {
      node.setNext(oldHead);
      if (ATOMIC_HELPER.casWaiters(this, oldHead, node)) {
        // we are on the stack, now wait for completion.
        while (true) {
          LockSupport.park(this);
          // Check interruption first, if we woke up due to interruption we need to honor that.
          if (Thread.interrupted()) {
            removeWaiter(node);
            throw new InterruptedException();
          }
          // Otherwise re-read and check doneness. If we loop then it must have been a spurious
          // wakeup
          localValue = value;
          if (localValue != null & !(localValue instanceof SetFuture)) {
            return getDoneValue(localValue);
          }
        }
      }
      oldHead = waiters; // re-read and loop.
    } while (oldHead != Waiter.TOMBSTONE);
  }
  // re-read value, if we get here then we must have observed a TOMBSTONE while trying to add a
  // waiter.
  return getDoneValue(value);
}
 
Example 11
Project: jdk8u-jdk   File: FutureTask.java   View Source Code Vote up 5 votes
/**
 * 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 12
Project: android-retrofuture   File: CompletableFuture.java   View Source Code Vote up 5 votes
public boolean block() {
    while (!isReleasable()) {
        if (deadline == 0L)
            LockSupport.park(this);
        else
            LockSupport.parkNanos(this, nanos);
    }
    return true;
}
 
Example 13
Project: game-executor   File: TestLockSupport.java   View Source Code Vote up 5 votes
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 14
Project: googles-monorepo-demo   File: AbstractFuture.java   View Source Code Vote up 5 votes
/**
 * {@inheritDoc}
 *
 * <p>The default {@link AbstractFuture} implementation throws {@code InterruptedException} if the
 * current thread is interrupted before or during the call, even if the value is already
 * available.
 *
 * @throws InterruptedException if the current thread was interrupted before or during the call
 *     (optional but recommended).
 * @throws CancellationException {@inheritDoc}
 */
@CanIgnoreReturnValue
@Override
public V get() throws InterruptedException, ExecutionException {
  if (Thread.interrupted()) {
    throw new InterruptedException();
  }
  Object localValue = value;
  if (localValue != null & !(localValue instanceof SetFuture)) {
    return getDoneValue(localValue);
  }
  Waiter oldHead = waiters;
  if (oldHead != Waiter.TOMBSTONE) {
    Waiter node = new Waiter();
    do {
      node.setNext(oldHead);
      if (ATOMIC_HELPER.casWaiters(this, oldHead, node)) {
        // we are on the stack, now wait for completion.
        while (true) {
          LockSupport.park(this);
          // Check interruption first, if we woke up due to interruption we need to honor that.
          if (Thread.interrupted()) {
            removeWaiter(node);
            throw new InterruptedException();
          }
          // Otherwise re-read and check doneness. If we loop then it must have been a spurious
          // wakeup
          localValue = value;
          if (localValue != null & !(localValue instanceof SetFuture)) {
            return getDoneValue(localValue);
          }
        }
      }
      oldHead = waiters; // re-read and loop.
    } while (oldHead != Waiter.TOMBSTONE);
  }
  // re-read value, if we get here then we must have observed a TOMBSTONE while trying to add a
  // waiter.
  return getDoneValue(value);
}
 
Example 15
Project: okdownload   File: RemitSyncToDBHelper.java   View Source Code Vote up 4 votes
void parkCurrentThread() {
    LockSupport.park();
}
 
Example 16
Project: okdownload   File: DownloadCall.java   View Source Code Vote up 4 votes
void parkForFirstConnection() {
    LockSupport.park();
}
 
Example 17
Project: monix-forkjoin   File: LinkedTransferQueue.java   View Source Code Vote up 4 votes
/**
 * 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) {
    long lastTime = timed ? System.nanoTime() : 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) {
            long now = System.nanoTime();
            if ((nanos -= now - lastTime) > 0)
                LockSupport.parkNanos(this, nanos);
            lastTime = now;
        }
        else {
            LockSupport.park(this);
        }
    }
}
 
Example 18
Project: jdk8u-jdk   File: LinkedTransferQueue.java   View Source Code Vote up 4 votes
/**
 * 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
Project: jdk8u-jdk   File: SynchronousQueue.java   View Source Code Vote up 4 votes
/**
 * 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
Project: reactive.loanbroker.system   File: JavaslangCircuitBreakerTests.java   View Source Code Vote up 3 votes
@Test
public void testCircuitBreaker() {

    ExecutorService executor = Executors.newSingleThreadExecutor();

    CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom()
            .failureRateThreshold(25)
            .waitDurationInOpenState(Duration.ofMillis(1000))
            .ringBufferSizeInHalfOpenState(2)
            .ringBufferSizeInClosedState(2)
            .build();

    CircuitBreaker circuitBreaker = CircuitBreaker.of("test",circuitBreakerConfig);

    Observable.interval(500, TimeUnit.MILLISECONDS).map((i)->{

        Try<String> result = null;

        if(i>10)
            result = functionWithTimeout(executor,true);
        else
            result = functionWithTimeout(executor,false);

        return result.get()+" : "+i;

    }).timeout(1500,TimeUnit.MILLISECONDS).lift(CircuitBreakerOperator.of(circuitBreaker)).subscribe(System.out::println);


    LockSupport.park();

}