本文整理汇总了Java中java.util.concurrent.locks.LockSupport类的典型用法代码示例。如果您正苦于以下问题:Java LockSupport类的具体用法?Java LockSupport怎么用?Java LockSupport使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
LockSupport类属于java.util.concurrent.locks包,在下文中一共展示了LockSupport类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: notifyClusterDDL
import java.util.concurrent.locks.LockSupport; //导入依赖的package包/类
public void notifyClusterDDL(String schema, String table, String sql, DDLInfo.DDLStatus ddlStatus, boolean needNotifyOther) throws Exception {
CuratorFramework zkConn = ZKUtils.getConnection();
DDLInfo ddlInfo = new DDLInfo(schema, sql, ZkConfig.getInstance().getValue(ZkParamCfg.ZK_CFG_MYID), ddlStatus);
String nodeName = StringUtil.getFullName(schema, table);
String nodePath = ZKPaths.makePath(KVPathUtil.getDDLPath(), nodeName);
if (zkConn.checkExists().forPath(nodePath) == null) {
zkConn.create().forPath(nodePath, ddlInfo.toString().getBytes(StandardCharsets.UTF_8));
} else {
String instancePath = ZKPaths.makePath(nodePath, KVPathUtil.DDL_INSTANCE);
String thisNode = ZkConfig.getInstance().getValue(ZkParamCfg.ZK_CFG_MYID);
ZKUtils.createTempNode(instancePath, thisNode);
if (needNotifyOther) {
//this node is ddl sender
zkConn.setData().forPath(nodePath, ddlInfo.toString().getBytes(StandardCharsets.UTF_8));
while (true) {
List<String> preparedList = zkConn.getChildren().forPath(instancePath);
List<String> onlineList = zkConn.getChildren().forPath(KVPathUtil.getOnlinePath());
if (preparedList.size() >= onlineList.size()) {
zkConn.delete().deletingChildrenIfNeeded().forPath(nodePath);
break;
}
LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(100));
}
}
}
}
示例2: ensureSyncComplete
import java.util.concurrent.locks.LockSupport; //导入依赖的package包/类
public void ensureSyncComplete(int blockIndex) {
final AtomicLong noSyncLength = noSyncLengthMap.get(blockIndex);
if (noSyncLength != null && noSyncLength.get() > 0) {
// sync to store
if (syncRunning) {
// wait for sync
parkThreadList.add(Thread.currentThread());
while (true) {
LockSupport.parkNanos(WAIT_SYNC_NANO);
if (!syncRunning) break;
}
}
// sync once, make sure data has been synced.
syncRunning = true;
syncRunnable.run();
}
}
示例3: testCircuitBreaker
import java.util.concurrent.locks.LockSupport; //导入依赖的package包/类
@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();
}
示例4: main
import java.util.concurrent.locks.LockSupport; //导入依赖的package包/类
public static void main(String[] args) throws InterruptedException{
new Thread(){
@Override
public void run() {
long writeLong=lock.writeLock();
LockSupport.parkNanos(600000000000L);
lock.unlockWrite(writeLong);
}
}.start();
Thread.sleep(100);
for(int i=0;i<3;++i){
holdCpuThreads[i]=new Thread(new HoldCPUReadThread());
holdCpuThreads[i].start();
}
Thread.sleep(10000);
//线程中断后,会占用CPU
for(int i=0;i<3;++i){
holdCpuThreads[i].interrupt();
}
int aa=0;
}
示例5: contendedLock
import java.util.concurrent.locks.LockSupport; //导入依赖的package包/类
/**
* Possibly blocks awaiting root lock.
*/
private final void contendedLock() {
boolean waiting = false;
for (int s;;) {
if (((s = lockState) & ~WAITER) == 0) {
if (U.compareAndSetInt(this, LOCKSTATE, s, WRITER)) {
if (waiting)
waiter = null;
return;
}
}
else if ((s & WAITER) == 0) {
if (U.compareAndSetInt(this, LOCKSTATE, s, s | WAITER)) {
waiting = true;
waiter = Thread.currentThread();
}
}
else if (waiting)
LockSupport.park(this);
}
}
示例6: handle
import java.util.concurrent.locks.LockSupport; //导入依赖的package包/类
public Reply handle(Command command) {
switch (command.code()) {
case Command.START:
return handleStart((StartCommand) command);
case Command.STOP:
return handleStop((StopCommand) command);
}
LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(responseLag));
switch (command.code()) {
case Command.ECHO:
return handleEcho((EchoCommand) command);
case Command.COUNT:
return handleCount((CountCommand) command);
case Command.REVERSE:
return handleReverse((ReverseCommand) command);
case Command.LOWER_CAST:
return handleLowerCast((LowerCastCommand) command);
case Command.UPPER_CAST:
return handleUpperCast((UpperCastCommand) command);
default:
throw new IllegalStateException();
}
}
示例7: finishCompletion
import java.util.concurrent.locks.LockSupport; //导入依赖的package包/类
/**
* 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
}
示例8: applyWaitMethod
import java.util.concurrent.locks.LockSupport; //导入依赖的package包/类
private int applyWaitMethod(final SequenceBarrier barrier, int counter)
throws AlertException {
//检查是否需要终止
barrier.checkAlert();
//如果在200~100,重试
if (counter > 100) {
--counter;
}
//如果在100~0,调用Thread.yield()让出CPU
else if (counter > 0) {
--counter;
Thread.yield();
}
//<0的话,利用LockSupport.parkNanos(1L)来sleep最小时间
else {
LockSupport.parkNanos(1L);
}
return counter;
}
示例9: testRemoveWaiter_interruption
import java.util.concurrent.locks.LockSupport; //导入依赖的package包/类
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();
}
示例10: testCpu
import java.util.concurrent.locks.LockSupport; //导入依赖的package包/类
public static void testCpu(){
long startTime = System.currentTimeMillis();
System.out.println(System.currentTimeMillis());
int number = 0;
while (true){
LockSupport.unpark(Thread.currentThread());
// LockSupport.park();
++number;
long currTime = System.currentTimeMillis();
if(number % 10000 == 0) {
LockSupport.park();
System.out.println("运行次数" + number + "时间" + (currTime - startTime));
}
}
}
示例11: testParkAfterUnpark
import java.util.concurrent.locks.LockSupport; //导入依赖的package包/类
public void testParkAfterUnpark(final ParkMethod parkMethod) {
final CountDownLatch pleaseUnpark = new CountDownLatch(1);
final AtomicBoolean pleasePark = new AtomicBoolean(false);
Thread t = newStartedThread(new CheckedRunnable() {
public void realRun() {
pleaseUnpark.countDown();
while (!pleasePark.get())
Thread.yield();
parkMethod.park();
}});
await(pleaseUnpark);
LockSupport.unpark(t);
pleasePark.set(true);
awaitTermination(t);
}
示例12: newHeaders
import java.util.concurrent.locks.LockSupport; //导入依赖的package包/类
/**
* Enqueue a batch of message headers
*
* @param p_headers
* the message headers
* @param p_messages
* the number of used entries in array
*/
void newHeaders(final MessageHeader[] p_headers, final int p_messages) {
// #ifdef STATISTICS
SOP_PUSH.enter();
// #endif /* STATISTICS */
if (!m_defaultMessageHeaders.pushMessageHeaders(p_headers, p_messages)) {
for (int i = 0; i < p_messages; i++) {
while (!m_defaultMessageHeaders.pushMessageHeader(p_headers[i])) {
// #ifdef STATISTICS
SOP_WAIT.enter();
// #endif /* STATISTICS */
LockSupport.parkNanos(100);
// #ifdef STATISTICS
SOP_WAIT.leave();
// #endif /* STATISTICS */
}
}
}
// #ifdef STATISTICS
SOP_PUSH.leave();
// #endif /* STATISTICS */
}
示例13: receivedBuffer
import java.util.concurrent.locks.LockSupport; //导入依赖的package包/类
@Override
public void receivedBuffer(final short p_sourceNodeId, final long p_bufferHandle, final long p_addr, final int p_length) {
// #if LOGGER >= TRACE
LOGGER.trace("Received buffer (0x%X, %d) from 0x%X", p_addr, p_length, p_sourceNodeId);
// #endif /* LOGGER >= TRACE */
IBConnection connection;
try {
connection = (IBConnection) getConnection(p_sourceNodeId);
} catch (final NetworkException e) {
// #if LOGGER >= ERROR
LOGGER.error("Getting connection for recv buffer of node 0x%X failed", p_sourceNodeId, e);
// #endif /* LOGGER >= ERROR */
return;
}
// Avoid congestion by not allowing more than m_numberOfBuffers buffers to be cached for reading
while (!m_incomingBufferQueue.pushBuffer(connection, null, p_bufferHandle, p_addr, p_length)) {
// #if LOGGER == TRACE
LOGGER.trace("Message creator: IncomingBuffer queue is full!");
// #endif /* LOGGER == TRACE */
//Thread.yield();
LockSupport.parkNanos(100);
}
}
示例14: waitAllSession
import java.util.concurrent.locks.LockSupport; //导入依赖的package包/类
private static boolean waitAllSession(ManagerConnection c, long timeout, long beginTime) {
logger.info("waiting all sessions of distributed transaction which are not finished.");
List<NonBlockingSession> fcList = getNeedWaitSession();
while (!fcList.isEmpty()) {
LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(10));
Iterator<NonBlockingSession> sListIterator = fcList.iterator();
while (sListIterator.hasNext()) {
NonBlockingSession session = sListIterator.next();
if (!session.isNeedWaitFinished()) {
sListIterator.remove();
}
}
if (c.isClosed()) {
errMsg = "client closed while waiting for unfinished distributed transactions.";
logger.info(errMsg);
return false;
}
if (TimeUtil.currentTimeMillis() > beginTime + timeout) {
errMsg = "timeout while waiting for unfinished distributed transactions.";
logger.info(errMsg);
return false;
}
}
logger.info("all sessions of distributed transaction are paused.");
return true;
}
示例15: contendedLock
import java.util.concurrent.locks.LockSupport; //导入依赖的package包/类
/**
* 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);
}
}