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

The following are Jave code examples for showing how to use unpark() 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: jdk8u-jdk   File: FutureTask.java   View Source Code Vote up 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 2
Project: openjdk-jdk10   File: FutureTask.java   View Source Code Vote up 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 (WAITERS.weakCompareAndSet(this, 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 3
Project: guava-mock   File: AbstractFutureTest.java   View Source Code Vote up 6 votes
public void testRemoveWaiter_interruption() throws Exception {
  final AbstractFuture<String> future = new AbstractFuture<String>() {};
  WaiterThread waiter1 = new WaiterThread(future);
  waiter1.start();
  waiter1.awaitWaiting();

  WaiterThread waiter2 = new WaiterThread(future);
  waiter2.start();
  waiter2.awaitWaiting();
  // The waiter queue should be waiter2->waiter1

  // This should wake up waiter1 and cause the waiter1 node to be removed.
  waiter1.interrupt();

  waiter1.join();
  waiter2.awaitWaiting();  // should still be blocked

  LockSupport.unpark(waiter2);  // spurious wakeup
  waiter2.awaitWaiting();  // should eventually re-park

  future.set(null);
  waiter2.join();
}
 
Example 4
Project: RLibrary   File: DownloadStatusCallback.java   View Source Code Vote up 6 votes
@Override
public boolean handleMessage(Message msg) {
    handlingMessage = true;
    final int status = msg.what;

    try {
        switch (status) {
            case FileDownloadStatus.progress:
                handleProgress(SystemClock.elapsedRealtime(), true);
                break;
            case FileDownloadStatus.retry:
                handleRetry((Exception) msg.obj, msg.arg1);
                break;
        }
    } finally {
        handlingMessage = false;
        if (parkThread != null) LockSupport.unpark(parkThread);
    }


    return true;
}
 
Example 5
Project: sstable-adaptor   File: WaitQueue.java   View Source Code Vote up 5 votes
private Thread signal()
{
    if (!isSet() && signalledUpdater.compareAndSet(this, NOT_SET, SIGNALLED))
    {
        Thread thread = this.thread;
        LockSupport.unpark(thread);
        this.thread = null;
        return thread;
    }
    return null;
}
 
Example 6
Project: okdownload   File: RemitSyncToDBHelper.java   View Source Code Vote up 5 votes
boolean dispatchDelayedMessage(int what) {
    if (what == WHAT_CLEAN_PARK) {
        if (parkThread != null) {
            LockSupport.unpark(parkThread);
            parkThread = null;
        }
        return true;
    }

    return false;
}
 
Example 7
Project: openjdk-jdk10   File: Phaser.java   View Source Code Vote up 5 votes
/**
 * Removes and signals threads from queue for phase.
 */
private void releaseWaiters(int phase) {
    QNode q;   // first element of queue
    Thread t;  // its thread
    AtomicReference<QNode> head = (phase & 1) == 0 ? evenQ : oddQ;
    while ((q = head.get()) != null &&
           q.phase != (int)(root.state >>> PHASE_SHIFT)) {
        if (head.compareAndSet(q, q.next) &&
            (t = q.thread) != null) {
            q.thread = null;
            LockSupport.unpark(t);
        }
    }
}
 
Example 8
Project: openjdk-jdk10   File: ForkJoinPool.java   View Source Code Vote up 5 votes
/**
 * Tries to create or release a worker if too few are running.
 */
final void signalWork() {
    for (;;) {
        long c; int sp; WorkQueue[] ws; int i; WorkQueue v;
        if ((c = ctl) >= 0L)                      // enough workers
            break;
        else if ((sp = (int)c) == 0) {            // no idle workers
            if ((c & ADD_WORKER) != 0L)           // too few workers
                tryAddWorker(c);
            break;
        }
        else if ((ws = workQueues) == null)
            break;                                // unstarted/terminated
        else if (ws.length <= (i = sp & SMASK))
            break;                                // terminated
        else if ((v = ws[i]) == null)
            break;                                // terminating
        else {
            int np = sp & ~UNSIGNALLED;
            int vp = v.phase;
            long nc = (v.stackPred & SP_MASK) | (UC_MASK & (c + RC_UNIT));
            Thread vt = v.owner;
            if (sp == vp && CTL.compareAndSet(this, c, nc)) {
                v.phase = np;
                if (v.source < 0)
                    LockSupport.unpark(vt);
                break;
            }
        }
    }
}
 
Example 9
Project: android-retroatomic   File: Phaser.java   View Source Code Vote up 5 votes
/**
 * Removes and signals threads from queue for phase.
 */
private void releaseWaiters(int phase) {
    QNode q;   // first element of queue
    Thread t;  // its thread
    AtomicReference<QNode> head = (phase & 1) == 0 ? evenQ : oddQ;
    while ((q = head.get()) != null &&
           q.phase != (int) (root.state >>> PHASE_SHIFT)) {
        if (head.compareAndSet(q, q.next) &&
            (t = q.thread) != null) {
            q.thread = null;
            LockSupport.unpark(t);
        }
    }
}
 
Example 10
Project: guava-mock   File: AbstractFuture.java   View Source Code Vote up 5 votes
void unpark() {
  // This is racy with removeWaiter. The consequence of the race is that we may spuriously call
  // unpark even though the thread has already removed itself from the list. But even if we did
  // use a CAS, that race would still exist (it would just be ever so slightly smaller).
  Thread w = thread;
  if (w != null) {
    thread = null;
    LockSupport.unpark(w);
  }
}
 
Example 11
Project: googles-monorepo-demo   File: AbstractFuture.java   View Source Code Vote up 5 votes
void unpark() {
  // This is racy with removeWaiter. The consequence of the race is that we may spuriously call
  // unpark even though the thread has already removed itself from the list. But even if we did
  // use a CAS, that race would still exist (it would just be ever so slightly smaller).
  Thread w = thread;
  if (w != null) {
    thread = null;
    LockSupport.unpark(w);
  }
}
 
Example 12
Project: openjdk-jdk10   File: CompletableFuture.java   View Source Code Vote up 5 votes
final CompletableFuture<?> tryFire(int ignore) {
    Thread w; // no need to atomically claim
    if ((w = thread) != null) {
        thread = null;
        LockSupport.unpark(w);
    }
    return null;
}
 
Example 13
Project: jdk8u-jdk   File: ConcurrentHashMap.java   View Source Code Vote up 5 votes
/**
 * Returns matching node or null if none. Tries to search
 * using tree comparisons from root, but continues linear
 * search when lock not available.
 */
final Node<K,V> find(int h, Object k) {
    if (k != null) {
        for (Node<K,V> e = first; e != null; ) {
            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;
                e = e.next;
            }
            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;
                    if (U.getAndAddInt(this, LOCKSTATE, -READER) ==
                        (READER|WAITER) && (w = waiter) != null)
                        LockSupport.unpark(w);
                }
                return p;
            }
        }
    }
    return null;
}
 
Example 14
Project: openjdk-jdk10   File: ConcurrentHashMap.java   View Source Code Vote up 5 votes
/**
 * Returns matching node or null if none. Tries to search
 * using tree comparisons from root, but continues linear
 * search when lock not available.
 */
final Node<K,V> find(int h, Object k) {
    if (k != null) {
        for (Node<K,V> e = first; e != null; ) {
            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;
                e = e.next;
            }
            else if (U.compareAndSetInt(this, LOCKSTATE, s,
                                         s + READER)) {
                TreeNode<K,V> r, p;
                try {
                    p = ((r = root) == null ? null :
                         r.findTreeNode(h, k, null));
                } finally {
                    Thread w;
                    if (U.getAndAddInt(this, LOCKSTATE, -READER) ==
                        (READER|WAITER) && (w = waiter) != null)
                        LockSupport.unpark(w);
                }
                return p;
            }
        }
    }
    return null;
}
 
Example 15
Project: OpenJSharp   File: LinkedTransferQueue.java   View Source Code Vote up 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;
}
 
Example 16
Project: jdk8u-jdk   File: SynchronousQueue.java   View Source Code Vote up 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 &&
        UNSAFE.compareAndSwapObject(this, matchOffset, 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 17
Project: util   File: ConcurrentHashMapV8.java   View Source Code Vote up 5 votes
/**
 * Returns matching node or null if none. Tries to search using tree
 * comparisons from root, but continues linear search when lock not
 * available.
 */
final Node<K, V> find(int h, Object k) {
	if (k != null) {
		for (Node<K, V> e = first; e != null;) {
			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;
				e = e.next;
			} 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 18
Project: okdownload   File: DownloadChain.java   View Source Code Vote up 4 votes
public void unparkOtherBlock() {
    LockSupport.unpark(parkThread);
    parkThread = null;
}
 
Example 19
Project: jdk8u-jdk   File: ThreadStateController.java   View Source Code Vote up 4 votes
private void nextState(int s) throws InterruptedException {
    final long id = Thread.currentThread().getId();
    log("%d: wait until the thread transitions to %s %s%n",
        id, toStateName(s), phaserToString(phaser));
    this.newState = s;
    int phase = phaser.arrive();
    log("%d:   awaiting party arrive %s %s%n",
        id, toStateName(s), phaserToString(phaser));
    for (;;) {
        // when this thread has changed its state before it waits or parks
        // on a lock, a potential race might happen if it misses the notify
        // or unpark.  Hence await for the phaser to advance with timeout
        // to cope with this race condition.
        switch (state) {
            case S_WAITING:
            case S_TIMED_WAITING:
                synchronized (lock) {
                    lock.notify();
                }
                break;
            case S_PARKED:
            case S_TIMED_PARKED:
                LockSupport.unpark(this);
                break;
            case S_SLEEPING:
                this.interrupt();
                break;
            case S_BLOCKED:
            default:
                break;
        }
        try {
            phaser.awaitAdvanceInterruptibly(phase, 100, TimeUnit.MILLISECONDS);
            log("%d:   arrived at %s %s%n",
                id, toStateName(s), phaserToString(phaser));
            return;
        } catch (TimeoutException ex) {
            // this thread hasn't arrived at this phase
            log("%d: Timeout: %s%n", id, phaser);
        }
    }
}
 
Example 20
Project: CustomLogger   File: NSLoggerClient.java   View Source Code Vote up 4 votes
@Override
public void run()
{
	// create the buffer file if needed
	try
	{
		if (DEBUG_LOGGER)
			Log.i("NSLogger", "Logging thread starting up");

		// Prepare to receive messages
		Looper.prepare();
		loggingThreadHandler = new InternalMsgHandler();

		// We are ready to run. Unpark the waiting threads now
		// (there may be multiple thread trying to start logging at the same time)
		ready.set(true);
		while (!readyWaiters.isEmpty())
			LockSupport.unpark(readyWaiters.poll());

		// Initial setup according to current parameters
		if (bufferFile != null)
			createBufferWriteStream();
		else if (remoteHost != null && remotePort != 0)
			connectToRemote();
		else if ((options & OPT_BROWSE_BONJOUR) != 0)
			setupBonjour();

		if (DEBUG_LOGGER)
			Log.i("NSLogger", "Logging thread looper starting");

		// Process messages
		Looper.loop();

		if (DEBUG_LOGGER)
			Log.i("NSLogger", "Logging thread looper ended");

		// Once loop exists, reset the variable (in case of problem we'll recreate a thread)
		closeBonjour();
		loggingThread = null;
		loggingThreadHandler = null;
	}
	catch (Exception e)
	{
		if (DEBUG_LOGGER)
			Log.e("NSLogger", "Exception caught in LoggingWorker.run(): " + e.toString());

		// In case an exception was caused before run, make sure waiters are unblocked
		ready.set(true);
		while (!readyWaiters.isEmpty())
			LockSupport.unpark(readyWaiters.peek());
	}
}