Java Code Examples for java.util.concurrent.locks.LockSupport

The following examples show how to use java.util.concurrent.locks.LockSupport. These examples are extracted from open source projects. 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
@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 2
Source Project: TNT4J   Source File: PooledLogger.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 3
Source Project: jocket   Source File: BenchClient.java    License: Apache License 2.0 6 votes vote down vote up
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 4
Source Project: protostuff   Source File: IncrementalIdStrategy.java    License: Apache License 2.0 6 votes vote down vote up
@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 5
Source Project: jdk-source-analysis   Source File: ThreadTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 6
Source Project: rpc-benchmark   Source File: WaitStrategy.java    License: Apache License 2.0 6 votes vote down vote up
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 7
Source Project: jdk1.8-source-analysis   Source File: FutureTask.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 Project: camunda-bpm-reactor   Source File: MpscDispatcher.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 9
Source Project: openjdk-8-source   Source File: StampedLock.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 10
Source Project: gemfirexd-oss   Source File: GfxdLockSet.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 Project: bucket4j   Source File: BlockingStrategy.java    License: Apache License 2.0 6 votes vote down vote up
@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 12
Source Project: openjdk-8   Source File: StampedLock.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 13
Source Project: dragonwell8_jdk   Source File: FutureTask.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 14
Source Project: openjdk-jdk8u   Source File: StampedLock.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 15
Source Project: reactor-core   Source File: FluxTests.java    License: Apache License 2.0 6 votes vote down vote up
@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 16
Source Project: cyclops   Source File: LimitWhileClosedOperatorTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 17
Source Project: jdk8u-jdk   Source File: StampedLock.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 18
Source Project: jdk-source-analysis   Source File: ThreadTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 Project: jdk8u60   Source File: LinkedTransferQueue.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 20
void doStateMaintenance() {
	
	while(!isShutdown()) {
		RunnableScheduledFuture<?> toSchedule;
		while((toSchedule = submittedScheduledTasks.poll()) != null)
			delayedTasks.add(toSchedule);
		RunnableScheduledFuture<?> toExecute;
		while((toExecute = delayedTasks.peek()) != null && toExecute.getDelay(TimeUnit.NANOSECONDS) <= 0) {
			delayedTasks.poll();
			immediateExecutor.executeWithoutWakeup(toExecute);
		}
		
		RunnableScheduledFuture<?> nextTask = delayedTasks.peek();

		// signal current thread as suspended before we actually check work queues.
		// this avoids wakeupWaiter() seeing an inconsistent state
		currentSleeper.set(Thread.currentThread());

		if(executorQueue.isEmpty() && submittedScheduledTasks.isEmpty()) {
			if(nextTask != null)
				LockSupport.parkNanos(nextTask.getDelay(TimeUnit.NANOSECONDS));
			else
				LockSupport.park();
			currentSleeper.set(null);
		} else {
			currentSleeper.set(null);
			// there are unmatched tasks in the queue, return this thread to the pool
			break;
		}
	}
	
	
	// reschedule if we fall out of loop
	if(!isShutdown())
		immediateExecutor.executeWithoutWakeup(scheduler);
}
 
Example 21
Source Project: gemfirexd-oss   Source File: SynchronousQueueNoSpin.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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 &&
        matchUpdater.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 22
Source Project: h2o-2   Source File: Phaser.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Variant of releaseWaiters that additionally tries to remove any
 * nodes no longer waiting for advance due to timeout or
 * interrupt. Currently, nodes are removed only if they are at
 * head of queue, which suffices to reduce memory footprint in
 * most usages.
 *
 * @return current phase on exit
 */
private int abortWait(int phase) {
    AtomicReference<QNode> head = (phase & 1) == 0 ? evenQ : oddQ;
    for (;;) {
        Thread t;
        QNode q = head.get();
        int p = (int)(root.state >>> PHASE_SHIFT);
        if (q == null || ((t = q.thread) != null && q.phase == p))
            return p;
        if (head.compareAndSet(q, q.next) && t != null) {
            q.thread = null;
            LockSupport.unpark(t);
        }
    }
}
 
Example 23
Source Project: multiway-pool   Source File: ConcurrentHashMapV8.java    License: Apache License 2.0 5 votes vote down vote up
/**
         * Returns matching node or null if none. Tries to search
         * using tree comparisons from root, but continues linear
         * search when lock not available.
         */
@Override
final Node<K,V> find(int h, Object k) {
            if (k != null) {
                for (Node<K,V> e = first; e != null; e = e.next) {
                    int s; K ek;
                    if (((s = lockState) & (WAITER|WRITER)) != 0) {
                        if (e.hash == h &&
                            ((ek = e.key) == k || (ek != null && k.equals(ek))))
                            return e;
                    }
                    else if (U.compareAndSwapInt(this, LOCKSTATE, s,
                                                 s + READER)) {
                        TreeNode<K,V> r, p;
                        try {
                            p = ((r = root) == null ? null :
                                 r.findTreeNode(h, k, null));
                        } finally {
                            Thread w;
                            int ls;
                            do {} while (!U.compareAndSwapInt
                                         (this, LOCKSTATE,
                                          ls = lockState, ls - READER));
                            if (ls == (READER|WAITER) && (w = waiter) != null)
                                LockSupport.unpark(w);
                        }
                        return p;
                    }
                }
            }
            return null;
        }
 
Example 24
Source Project: hottub   Source File: CompletableFuture.java    License: GNU General Public License v2.0 5 votes vote down vote up
final CompletableFuture<?> tryFire(int ignore) {
    Thread w; // no need to atomically claim
    if ((w = thread) != null) {
        thread = null;
        LockSupport.unpark(w);
    }
    return null;
}
 
Example 25
Source Project: copper-engine   Source File: GitWorkflowRepositoryTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void changeGitRepositoryFailureDirTest() throws Exception {
    wfRepo.setGitRepositoryDir(WORK_DIR + "/wf-source2");
    LockSupport.parkNanos(1000000000 + CHECK_INTERVAL_M_SEC * 1000000); // wait for workflow refresh
    defaultBranchTest();
    wfRepo.setBranch("1.0");
    LockSupport.parkNanos(1000000000 + CHECK_INTERVAL_M_SEC * 1000000); // wait for workflow refresh
    engine.run("Workflow1", "foo");
    String result1 = (String) channel.wait("correlationId", 1000, TimeUnit.MILLISECONDS);
    assertEquals("new branch not loaded, so expect Vmaster", "Vmaster", result1);
}
 
Example 26
Source Project: dble   Source File: AbstractClusterSender.java    License: GNU General Public License v2.0 5 votes vote down vote up
public String waitingForAllTheNode(String checkString, String path) {
    Map<String, String> expectedMap = ClusterToXml.getOnlineMap();
    StringBuffer errorMsg = new StringBuffer();
    for (; ; ) {
        errorMsg.setLength(0);
        if (checkResponseForOneTime(checkString, path, expectedMap, errorMsg)) {
            break;
        }
        LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(50));
    }
    return errorMsg.length() <= 0 ? null : errorMsg.toString();
}
 
Example 27
Source Project: JDKSourceCode1.8   Source File: LinkedTransferQueue.java    License: MIT License 5 votes vote down vote up
/**
 * 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;
}
 
Example 28
public void start() {
    try {
        channel.basicQos(options.prefetchSize);
        channel.basicConsume(queue, false, this);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
    LockSupport.park();
}
 
Example 29
/**
 * 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;
}
 
Example 30
/**
 * 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;
}