java.util.concurrent.locks.LockSupport Java Examples
The following examples show how to use
java.util.concurrent.locks.LockSupport.
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: FluxTests.java From reactor-core with Apache License 2.0 | 6 votes |
@Test public void fluxCreateDemoElasticScheduler() throws Exception { final int inputCount = 1000; final CountDownLatch latch = new CountDownLatch(inputCount); Flux.create( sink -> { for (int i = 0; i < inputCount; i++) { sink.next(i); } sink.complete(); }). subscribeOn(Schedulers.newSingle("production")). publishOn(Schedulers.boundedElastic()). subscribe(i -> { LockSupport.parkNanos(100L); latch.countDown(); }); latch.await(); }
Example #2
Source File: BenchClient.java From jocket with Apache License 2.0 | 6 votes |
private long doRun(String msg, int reps, long pauseNanos) throws IOException { System.out.printf("%-15s: %10d reps, pause between reps: %dns...", msg, reps, pauseNanos); long time = System.currentTimeMillis(); for (int i = 0; i < reps; i++) { long nanos = System.nanoTime(); iter(BATCH); nanos = (System.nanoTime() - nanos) / BATCH; if (!NOSTATS && i < this.nanos.length) this.nanos[i % reps] = nanos; if (pauseNanos > 0) LockSupport.parkNanos(pauseNanos); } time = System.currentTimeMillis() - time; System.out.printf(" done in %dms\n", time); return time; }
Example #3
Source File: IncrementalIdStrategy.java From protostuff with Apache License 2.0 | 6 votes |
@Override protected <T> HasSchema<T> tryWritePojoIdTo(Output output, int fieldNumber, Class<T> clazz, boolean registered) throws IOException { BaseHS<T> wrapper = getBaseHS(clazz, false); if (wrapper == null || (registered && !(wrapper instanceof Registered))) return null; int id; // wait till everything is completely set while (0 == (id = wrapper.id)) LockSupport.parkNanos(1); output.writeUInt32(fieldNumber, id, false); return wrapper; }
Example #4
Source File: ThreadTest.java From jdk-source-analysis with Apache License 2.0 | 6 votes |
@Test public void testInterruptAction() { Thread thread = new Thread(() -> { while (true) { Thread.yield(); // 响应中断 if (Thread.currentThread().isInterrupted()) { System.out.println("Java技术栈线程被中断,程序退出。"); return; } } }); thread.start(); thread.interrupt(); LockSupport.parkNanos(TimeUnit.MINUTES.toNanos(1)); }
Example #5
Source File: BlockingStrategy.java From bucket4j with Apache License 2.0 | 6 votes |
@Override public void park(final long nanosToPark) throws InterruptedException { final long endNanos = System.nanoTime() + nanosToPark; long remainingParkNanos = nanosToPark; while (true) { LockSupport.parkNanos(remainingParkNanos); long currentTimeNanos = System.nanoTime(); remainingParkNanos = endNanos - currentTimeNanos; if (Thread.interrupted()) { throw new InterruptedException(); } if (remainingParkNanos <= 0) { return; } } }
Example #6
Source File: StampedLock.java From openjdk-8 with GNU General Public License v2.0 | 6 votes |
/** * Tries to decrement readerOverflow. * * @param s a reader overflow stamp: (s & ABITS) >= RFULL * @return new stamp on success, else zero */ private long tryDecReaderOverflow(long s) { // assert (s & ABITS) >= RFULL; if ((s & ABITS) == RFULL) { if (U.compareAndSwapLong(this, STATE, s, s | RBITS)) { int r; long next; if ((r = readerOverflow) > 0) { readerOverflow = r - 1; next = s; } else next = s - RUNIT; state = next; return next; } } else if ((LockSupport.nextSecondarySeed() & OVERFLOW_YIELD_RATE) == 0) Thread.yield(); return 0L; }
Example #7
Source File: FutureTask.java From dragonwell8_jdk with GNU General Public License v2.0 | 6 votes |
/** * Removes and signals all waiting threads, invokes done(), and * nulls out callable. */ private void finishCompletion() { // assert state > COMPLETING; for (WaitNode q; (q = waiters) != null;) { if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) { for (;;) { Thread t = q.thread; if (t != null) { q.thread = null; LockSupport.unpark(t); } WaitNode next = q.next; if (next == null) break; q.next = null; // unlink to help gc q = next; } break; } } done(); callable = null; // to reduce footprint }
Example #8
Source File: StampedLock.java From openjdk-jdk8u with GNU General Public License v2.0 | 6 votes |
/** * Tries to decrement readerOverflow. * * @param s a reader overflow stamp: (s & ABITS) >= RFULL * @return new stamp on success, else zero */ private long tryDecReaderOverflow(long s) { // assert (s & ABITS) >= RFULL; if ((s & ABITS) == RFULL) { if (U.compareAndSwapLong(this, STATE, s, s | RBITS)) { int r; long next; if ((r = readerOverflow) > 0) { readerOverflow = r - 1; next = s; } else next = s - RUNIT; state = next; return next; } } else if ((LockSupport.nextSecondarySeed() & OVERFLOW_YIELD_RATE) == 0) Thread.yield(); return 0L; }
Example #9
Source File: WaitStrategy.java From rpc-benchmark with Apache License 2.0 | 6 votes |
public final int idle(final int idleCounter) { final int idled = idleCounter + 1; if (idleCounter < 10) { Thread.onSpinWait(); return idled; } if (idleCounter < 10 + 10) { Thread.yield(); return idled; } LockSupport.parkNanos(1L); return idled; }
Example #10
Source File: GfxdLockSet.java From gemfirexd-oss with Apache License 2.0 | 6 votes |
/** * Method to be invoked from an {@link GfxdResultCollector} when it has * completed to signal any waiting thread that invoked {@link #rcWaiter}. */ public void rcEnd(final GfxdResultCollector<?> rc) { final GfxdResultCollector<?> pendingRC = this.pendingRC; if (pendingRC != null) { if (rc == null || rc == pendingRC) { final Thread waiter = this.rcWaiter; this.pendingRC = null; if (waiter != null) { LockSupport.unpark(waiter); } if (GemFireXDUtils.TraceLock) { SanityManager.DEBUG_PRINT(GfxdConstants.TRACE_LOCK, toString() + "#rcEnd: cleared ResultCollector: " + rc + ", pending thread: " + waiter); } } else { if (GemFireXDUtils.TraceLock) { SanityManager.DEBUG_PRINT(GfxdConstants.TRACE_LOCK, toString() + "#rcEnd: ignored ResultCollector: " + rc + ", for pendingRC: " + pendingRC); } } } }
Example #11
Source File: LimitWhileClosedOperatorTest.java From cyclops with Apache License 2.0 | 6 votes |
@Test public void predicateErrorAsync(){ AtomicReference<Vector<Integer>> data = new AtomicReference(Vector.empty()); AtomicBoolean complete = new AtomicBoolean(false); AtomicReference<Throwable> error = new AtomicReference<Throwable>(null); Spouts.async(ReactiveSeq.of(1,2,3,4,5),ex) .takeWhileInclusive(i ->{ throw new RuntimeException();}) .forEach(n->{ assertFalse(complete.get()); data.updateAndGet(s->s.plus(n)); },e->{ error.set(e); },()->{ complete.set(true); }); while(!complete.get()){ LockSupport.parkNanos(10l); } assertThat(data.get(),equalTo(Vector.of())); assertThat(complete.get(),equalTo(true)); assertThat(error.get(),instanceOf(RuntimeException.class)); }
Example #12
Source File: PooledLogger.java From TNT4J with Apache License 2.0 | 6 votes |
/** * Handle event signal processing * * @param event * event instance * @throws IOException */ private void handleSignal(SinkLogEvent event) throws IOException { Thread signal = event.getSignal(); try { signalCount.incrementAndGet(); if (event.getSignalType() == SinkLogEvent.SIGNAL_CLOSE) { close(event.getEventSink()); } else if (event.getSignalType() == SinkLogEvent.SIGNAL_FLUSH) { event.getEventSink().flush(); } else if (event.getSignalType() == SinkLogEvent.SIGNAL_SHUTDOWN) { shutdown(event.getException()); close(event.getEventSink()); } } finally { LockSupport.unpark(signal); } }
Example #13
Source File: StampedLock.java From jdk8u-jdk with GNU General Public License v2.0 | 6 votes |
/** * Tries to decrement readerOverflow. * * @param s a reader overflow stamp: (s & ABITS) >= RFULL * @return new stamp on success, else zero */ private long tryDecReaderOverflow(long s) { // assert (s & ABITS) >= RFULL; if ((s & ABITS) == RFULL) { if (U.compareAndSwapLong(this, STATE, s, s | RBITS)) { int r; long next; if ((r = readerOverflow) > 0) { readerOverflow = r - 1; next = s; } else next = s - RUNIT; state = next; return next; } } else if ((LockSupport.nextSecondarySeed() & OVERFLOW_YIELD_RATE) == 0) Thread.yield(); return 0L; }
Example #14
Source File: RollingRandomAccessFileManagerTest.java From logging-log4j2 with Apache License 2.0 | 6 votes |
@Test public void testFileTimeBasedOnFileModifiedTimeWhenAppendIsTrue() throws IOException { final File file = File.createTempFile("log4j2", "test"); file.deleteOnExit(); LockSupport.parkNanos(1000000); // 1 millisec final boolean isAppend = true; assertThat(file, lastModified(beforeNow())); final RollingRandomAccessFileManager manager = RollingRandomAccessFileManager.getRollingRandomAccessFileManager( // file.getAbsolutePath(), Strings.EMPTY, isAppend, true, RollingRandomAccessFileManager.DEFAULT_BUFFER_SIZE, new SizeBasedTriggeringPolicy(Long.MAX_VALUE), // null, null, null, null, null, null, null); assertThat(file, lastModified(equalTo(manager.getFileTime()))); }
Example #15
Source File: StampedLock.java From openjdk-8-source with GNU General Public License v2.0 | 6 votes |
/** * Tries to decrement readerOverflow. * * @param s a reader overflow stamp: (s & ABITS) >= RFULL * @return new stamp on success, else zero */ private long tryDecReaderOverflow(long s) { // assert (s & ABITS) >= RFULL; if ((s & ABITS) == RFULL) { if (U.compareAndSwapLong(this, STATE, s, s | RBITS)) { int r; long next; if ((r = readerOverflow) > 0) { readerOverflow = r - 1; next = s; } else next = s - RUNIT; state = next; return next; } } else if ((LockSupport.nextSecondarySeed() & OVERFLOW_YIELD_RATE) == 0) Thread.yield(); return 0L; }
Example #16
Source File: MpscDispatcher.java From camunda-bpm-reactor with Apache License 2.0 | 6 votes |
/** * Creates a new {@code MpscDispatcher} with the given {@code name}. It will use a MpscLinkedQueue and a virtual capacity of {code bufferSize} * * @param name The name of the dispatcher * @param bufferSize The size to configure the ring buffer with */ @SuppressWarnings({"unchecked"}) public MpscDispatcher(String name, int bufferSize) { super(bufferSize); this.executor = Executors.newSingleThreadExecutor(new NamedDaemonThreadFactory(name, getContext())); this.workQueue = MpscLinkedQueue.create(); this.capacity = bufferSize; this.executor.execute(() -> { Task task; try { for (; ; ) { task = workQueue.poll(); if (null != task) { task.run(); } else { LockSupport.parkNanos(1l); //TODO expose } } } catch (EndException e) { //ignore } }); }
Example #17
Source File: FutureTask.java From jdk1.8-source-analysis with Apache License 2.0 | 6 votes |
/** * Removes and signals all waiting threads, invokes done(), and * nulls out callable. */ private void finishCompletion() { // assert state > COMPLETING; for (WaitNode q; (q = waiters) != null;) { if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) { for (;;) { Thread t = q.thread; if (t != null) { q.thread = null; LockSupport.unpark(t); } WaitNode next = q.next; if (next == null) break; q.next = null; // unlink to help gc q = next; } break; } } done(); callable = null; // to reduce footprint }
Example #18
Source File: ThreadTest.java From jdk-source-analysis with Apache License 2.0 | 6 votes |
@Test public void testInterruptStatus1() throws InterruptedException { class InterruptTask implements Runnable { @Override public void run() { long i = 0; while (true) { i++; } } } Thread thread = new Thread(new InterruptTask()); thread.start(); Thread.sleep(1000); thread.interrupt(); System.out.println("thread.isInterrupted() = " + thread.isInterrupted()); System.out.println("thread.isInterrupted() = " + thread.isInterrupted()); LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(2)); }
Example #19
Source File: CompletableFuture.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
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 #20
Source File: CompletableFuture.java From Bytecoder with Apache License 2.0 | 5 votes |
public boolean block() { while (!isReleasable()) { if (deadline == 0L) LockSupport.park(this); else LockSupport.parkNanos(this, nanos); } return true; }
Example #21
Source File: Phaser.java From streamsupport with GNU General Public License v2.0 | 5 votes |
public boolean block() { while (!isReleasable()) { if (timed) { LockSupport.parkNanos(this, nanos); } else { LockSupport.park(this); } } return true; }
Example #22
Source File: QueuedSynchronizer.java From gemfirexd-oss with Apache License 2.0 | 5 votes |
/** * Acquires in shared timed mode. * * @param arg * the acquire argument * @param ownerId * the lock owner, if any * @param lock * the {@link TryLockObject} that will encapsulate the state of lock * @param nanosTimeout * max wait time * @param context * Any context object can be provided here (that can be passed to * methods like * {@link ExclusiveSharedSynchronizer#getOwnerId(Object)} by * implementations of {@link TryLockObject}). * * @return {@code true} if acquired */ private boolean doAcquireSharedNanos(final int arg, final Object ownerId, final TryLockObject lock, long nanosTimeout, final Object context, final CancelCriterion cc) { if (nanosTimeout <= 0L) return false; final long deadline = System.nanoTime() + nanosTimeout; final Node node = addWaiter(Node.SHARED); boolean failed = true; try { for (;;) { final Node p = node.predecessor(); if (p == this.head) { final int r = lock.tryAcquireShared(arg, ownerId, context); if (r >= 0) { setHeadAndPropagate(node, r); p.next = null; // help GC failed = false; return true; } } nanosTimeout = deadline - System.nanoTime(); if (nanosTimeout <= 0L) return false; if (shouldParkAfterFailedAcquire(p, node) && nanosTimeout > spinForTimeoutThreshold) LockSupport.parkNanos(this, nanosTimeout); if (Thread.interrupted()) { handleInterrupted(cc); return false; } } } finally { if (failed) { cancelAcquire(node); } } }
Example #23
Source File: ResultFuture.java From baratine with GNU General Public License v2.0 | 5 votes |
@Override public <U> void completeFuture(ResultChain<U> chain, U chainValue) { _chain = (Result) chain; _chainValue = chainValue; _state = FutureState.ASYNC; Thread thread = _thread; if (thread != null) { LockSupport.unpark(thread); } }
Example #24
Source File: OldDeletedEntriesCleanupThread.java From Chronicle-Map with Apache License 2.0 | 5 votes |
@Override public void close() { shutdown = true; // this means blocked in sleepMillis() or sleepNanos() if (LockSupport.getBlocker(this) == cleanupSleepingHandle) this.interrupt(); // unblock }
Example #25
Source File: ValueSubscriber.java From cyclops with Apache License 2.0 | 5 votes |
private T throwingGet() { while (firstValue.get() == UNSET && firstError.get() == UNSET) LockSupport.parkNanos(1000000l); if (firstValue.get() == UNSET) throw ExceptionSoftener.throwSoftenedException((Throwable) firstError.get()); return (T) firstValue.get(); }
Example #26
Source File: SynchronousQueue.java From Bytecoder with Apache License 2.0 | 5 votes |
/** * Tries to match node s to this node, if so, waking up thread. * Fulfillers call tryMatch to identify their waiters. * Waiters block until they have been matched. * * @param s the node to match * @return true if successfully matched to s */ boolean tryMatch(SNode s) { if (match == null && SMATCH.compareAndSet(this, null, s)) { Thread w = waiter; if (w != null) { // waiters need at most one unpark waiter = null; LockSupport.unpark(w); } return true; } return match == s; }
Example #27
Source File: DelayedDummyTransport.java From deeplearning4j with Apache License 2.0 | 5 votes |
@Override public void sendMessage(@NonNull VoidMessage message, @NonNull String id) { val bos = new ByteArrayOutputStream(); synchronized (this) { SerializationUtils.serialize(message, bos); } val bis = new ByteArrayInputStream(bos.toByteArray()); final VoidMessage msg = SerializationUtils.deserialize(bis); if (msg.getOriginatorId() == null) msg.setOriginatorId(this.id()); //super.sendMessage(message, id); connector.executorService().submit(new Runnable() { @Override public void run() { try { // imitate some bad network here, latency of 0.05ms - 0.2ms val sleepTime = RandomUtils.nextInt(50, 200) * 1000; LockSupport.parkNanos(sleepTime); DelayedDummyTransport.super.sendMessage(msg, id); } catch (Exception e) { log.error("Got exception: ", e); } } }); //super.sendMessage(msg, id); }
Example #28
Source File: LogBuffer.java From baratine with GNU General Public License v2.0 | 5 votes |
public final void clear() { _length = 0; Thread thread = _thread; if (thread != null) { LockSupport.unpark(thread); } }
Example #29
Source File: GatewayEventStore.java From DataLink with Apache License 2.0 | 5 votes |
/** * 必须所有store都put成功之后再返回,避免外部重试导致单个store一直重复put */ @SuppressWarnings("unchecked") private boolean doPut(List data) throws CanalStoreException { succeededStores.clear(); isSuspend = false; startTime = System.currentTimeMillis(); while (running && !interrupted) { if (!isSuspend) { Map<String, CanalEventStore> stores = Maps.newHashMap(attachedEventStores); if (stores.isEmpty()) { return false; } boolean result = true; for (String key : stores.keySet()) { if (!succeededStores.containsKey(key)) { boolean putResult = stores.get(key).tryPut(data); if (putResult) { succeededStores.put(key, stores.get(key)); } result &= putResult; } } if (result) { return true; } if (System.currentTimeMillis() - startTime > 1000 * 60 * 1) { isSuspend = true; } } //100ms LockSupport.parkNanos(1000 * 1000L * 100); } return false; }
Example #30
Source File: LinkedTransferQueue.java From jdk8u60 with GNU General Public License v2.0 | 5 votes |
/** * Tries to artificially match a data node -- used by remove. */ final boolean tryMatchData() { // assert isData; Object x = item; if (x != null && x != this && casItem(x, null)) { LockSupport.unpark(waiter); return true; } return false; }