當前位置: 首頁>>代碼示例>>Java>>正文


Java Semaphore.tryAcquire方法代碼示例

本文整理匯總了Java中java.util.concurrent.Semaphore.tryAcquire方法的典型用法代碼示例。如果您正苦於以下問題:Java Semaphore.tryAcquire方法的具體用法?Java Semaphore.tryAcquire怎麽用?Java Semaphore.tryAcquire使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在java.util.concurrent.Semaphore的用法示例。


在下文中一共展示了Semaphore.tryAcquire方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: getSnap

import java.util.concurrent.Semaphore; //導入方法依賴的package包/類
public static DataSnapshot getSnap(Query ref) throws InterruptedException {

    final Semaphore semaphore = new Semaphore(0);

    // Hack to get around final reference issue
    final List<DataSnapshot> snapshotList = new ArrayList<>(1);

    ref.addListenerForSingleValueEvent(
        new ValueEventListener() {
          @Override
          public void onDataChange(DataSnapshot snapshot) {
            snapshotList.add(snapshot);
            semaphore.release(1);
          }

          @Override
          public void onCancelled(DatabaseError error) {
            semaphore.release(1);
          }
        });

    semaphore.tryAcquire(1, TestUtils.TEST_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
    return snapshotList.get(0);
  }
 
開發者ID:firebase,項目名稱:firebase-admin-java,代碼行數:25,代碼來源:TestHelpers.java

示例2: waitForProcessedStoring

import java.util.concurrent.Semaphore; //導入方法依賴的package包/類
@Override
public void waitForProcessedStoring(VCSFileProxy file, String caller) {
    Semaphore s;
    synchronized(proccessedFiles) {
        s = proccessedFiles.get(file);
    }
    if(s != null) {
        long l = System.currentTimeMillis();
        try {
            long t9Timeout = getT9LockReleaseTimeOut();
            long timeout = t9Timeout >= 0 ? t9Timeout : LOCK_TIMEOUT;
            boolean aquired = s.tryAcquire(timeout, TimeUnit.SECONDS);
            if(aquired) {
                s.release();
            } else {
                LOG.log(Level.WARNING, "{0} Releasing lock on file: {1}", new Object[] {caller, FileUtils.getPath(file)}); // NOI18N
                synchronized(proccessedFiles) {
                    proccessedFiles.remove(file);
                }
            }
        } catch (InterruptedException ex) {
            // nothing
        }
        LOG.log(Level.FINER, "{0} for file {1} was blocked {2} millis.", new Object[] {caller, FileUtils.getPath(file), System.currentTimeMillis() - l}); // NOI18N
    }
}
 
開發者ID:apache,項目名稱:incubator-netbeans,代碼行數:27,代碼來源:LocalHistoryStoreImpl.java

示例3: waitForResponse

import java.util.concurrent.Semaphore; //導入方法依賴的package包/類
private ActionResponseData waitForResponse(ActionRequestData requestData, long timeout) {
    Semaphore semaphore = new Semaphore(0);
    AtomicReference<ActionResponseData> response = new AtomicReference<>();
    actionHandler.addActionRequest(requestData, actionResponseData -> {
        response.compareAndSet(null, actionResponseData);
        semaphore.release();
    });
    try {
        if(semaphore.tryAcquire(timeout, TimeUnit.MILLISECONDS)) {
            return response.get();
        } else {
            LOGGER.warn("Action response timed out");
        }
    } catch (InterruptedException e) {
        LOGGER.warn("Action response interrupted", e);
    }
    return null;
}
 
開發者ID:jhkst,項目名稱:dlface,代碼行數:19,代碼來源:FrdDialogSupportImpl.java

示例4: enterIOCriticalSection

import java.util.concurrent.Semaphore; //導入方法依賴的package包/類
public void enterIOCriticalSection(String key) throws IOException {
    // http://dmy999.com/article/34/correct-use-of-concurrenthashmap
    Semaphore creationSemaphore = map.get(key);
    if(creationSemaphore == null) {
        Semaphore newCreationSemaphore = new Semaphore(1, true);
        creationSemaphore = map.putIfAbsent(key, newCreationSemaphore);
        if(creationSemaphore == null) {
            creationSemaphore = newCreationSemaphore;       
            if (logger.isLoggingEnabled(StackLogger.TRACE_DEBUG)) {
                logger.logDebug("new Semaphore added for key " + key);
            }
        }
    }
    
    try {
        boolean retval = creationSemaphore.tryAcquire(10, TimeUnit.SECONDS);
        if (!retval) {
            throw new IOException("Could not acquire IO Semaphore'" + key
                    + "' after 10 seconds -- giving up ");
        }
    } catch (InterruptedException e) {
        throw new IOException("exception in acquiring sem");
    }
}
 
開發者ID:YunlongYang,項目名稱:LightSIP,代碼行數:25,代碼來源:KeyedSemaphore.java

示例5: doTestUnloadableInStaticFieldIfClosed

import java.util.concurrent.Semaphore; //導入方法依賴的package包/類
private WeakReference<ClassLoader> doTestUnloadableInStaticFieldIfClosed() throws Exception {
  final URLClassLoader myLoader = (URLClassLoader) getClass().getClassLoader();
  final URL[] urls = myLoader.getURLs();
  URLClassLoader sepLoader = new URLClassLoader(urls, myLoader.getParent());

  Class<?> frqC = FinalizableReferenceQueue.class;
  Class<?> sepFrqC = sepLoader.loadClass(frqC.getName());
  assertNotSame(frqC, sepFrqC);

  Class<?> sepFrqSystemLoaderC =
      sepLoader.loadClass(FinalizableReferenceQueue.SystemLoader.class.getName());
  Field disabled = sepFrqSystemLoaderC.getDeclaredField("disabled");
  disabled.setAccessible(true);
  disabled.set(null, true);

  Class<?> frqUserC = FrqUser.class;
  Class<?> sepFrqUserC = sepLoader.loadClass(frqUserC.getName());
  assertNotSame(frqUserC, sepFrqUserC);
  assertSame(sepLoader, sepFrqUserC.getClassLoader());

  Callable<?> sepFrqUser = (Callable<?>) sepFrqUserC.newInstance();
  WeakReference<?> finalizableWeakReference = (WeakReference<?>) sepFrqUser.call();

  GcFinalization.awaitClear(finalizableWeakReference);

  Field sepFrqUserFinalizedF = sepFrqUserC.getField("finalized");
  Semaphore finalizeCount = (Semaphore) sepFrqUserFinalizedF.get(null);
  boolean finalized = finalizeCount.tryAcquire(5, TimeUnit.SECONDS);
  assertTrue(finalized);

  Field sepFrqUserFrqF = sepFrqUserC.getField("frq");
  Closeable frq = (Closeable) sepFrqUserFrqF.get(null);
  frq.close();

  return new WeakReference<ClassLoader>(sepLoader);
}
 
開發者ID:paul-hammant,項目名稱:googles-monorepo-demo,代碼行數:37,代碼來源:FinalizableReferenceQueueClassLoaderUnloadingTest.java

示例6: checkTreeCache

import java.util.concurrent.Semaphore; //導入方法依賴的package包/類
private static void checkTreeCache(CuratorFramework curatorFramework, String path) throws Exception {
    final Semaphore semaphore = new Semaphore(0);
    TreeCache treeCache = TreeCache.newBuilder(curatorFramework, path)
            .setCacheData(true)
            .setMaxDepth(3)
            .build();

    if (treeCache == null) {
        LOGGER.error("treeCache is null");
    }

    treeCache.getListenable().addListener((client, event) -> {
        if (event.getType().equals(TreeCacheEvent.Type.INITIALIZED)) {
            semaphore.release();
        }
    });

    treeCache.start();

    semaphore.tryAcquire(2, TimeUnit.SECONDS);


    Map<String, ChildData> map = treeCache.getCurrentChildren("/propertyService");

   if (map == null) {
       LOGGER.error("map is null");
   }

    map.entrySet().forEach(entry -> {
        LOGGER.info("{} - {}", entry.getKey(), Bytes.toString(entry.getValue().getData()));
    });
}
 
開發者ID:gchq,項目名稱:stroom-stats,代碼行數:33,代碼來源:CuratorTest.java

示例7: retrievePayment

import java.util.concurrent.Semaphore; //導入方法依賴的package包/類
@RequestMapping(path = "/api/payment/v5", method = PUT)
public String retrievePayment(String retrievePaymentPayload, HttpServletResponse response) throws Exception {
  String traceId = UUID.randomUUID().toString();
  String customerId = "0815"; // get somehow from retrievePaymentPayload
  long amount = 15; // get somehow from retrievePaymentPayload

  Semaphore newSemaphore = NotifySemaphorAdapter.newSemaphore(traceId);
  
  ProcessInstance pi = retrievePayment(traceId, customerId, amount);
  
  boolean finished = newSemaphore.tryAcquire(500, TimeUnit.MILLISECONDS);
  NotifySemaphorAdapter.removeSemaphore(traceId);
  
  if (finished) {
    HistoricVariableInstance historicVariableInstance = camunda.getHistoryService().createHistoricVariableInstanceQuery()
        .processInstanceId(pi.getId()) //
        .variableName("paymentTransactionId") //
        .singleResult();
      if (historicVariableInstance!=null) {
        String paymentTransactionId = (String)historicVariableInstance.getValue(); 
        return "{\"status\":\"completed\", \"traceId\": \"" + traceId + "\", \"paymentTransactionId\": \""+paymentTransactionId+"\"}";
      } else {
        return "{\"status\":\"completed\", \"traceId\": \"" + traceId + "\", \"payedByCredit\": \"true\"}";        
      }
  } else {
    response.setStatus(HttpServletResponse.SC_ACCEPTED);
    return "{\"status\":\"pending\", \"traceId\": \"" + traceId + "\"}";
  }    
}
 
開發者ID:flowing,項目名稱:flowing-retail,代碼行數:30,代碼來源:PaymentRestHacksControllerV5.java

示例8: testExecuteWritesStdoutToTheStdoutListener

import java.util.concurrent.Semaphore; //導入方法依賴的package包/類
@Test
public void testExecuteWritesStdoutToTheStdoutListener() throws Throwable {
    final JobExecutor jobExecutor = getInstance();
    final String msgSuppliedToEcho = generateRandomString();
    final PersistedJob req =
            standardRequestWithCommand("echo", msgSuppliedToEcho);
    final AtomicReference<byte[]> bytesEchoedToStdout = new AtomicReference<>(new byte[]{});
    final Subject<byte[]> stdoutSubject = PublishSubject.create();

    stdoutSubject.subscribe(bytes ->
            bytesEchoedToStdout.getAndUpdate(existingBytes ->
                    Bytes.concat(existingBytes, bytes)));

    final Semaphore s = new Semaphore(1);
    s.acquire();
    stdoutSubject.doOnComplete(s::release).subscribe();

    final JobEventListeners listeners =
            createStdoutListener(stdoutSubject);

    jobExecutor.execute(req, listeners);

    s.tryAcquire(TestConstants.DEFAULT_TIMEOUT, MILLISECONDS);

    final String stringFromStdout = new String(bytesEchoedToStdout.get()).trim();
    assertThat(stringFromStdout).isEqualTo(msgSuppliedToEcho);
}
 
開發者ID:adamkewley,項目名稱:jobson,代碼行數:28,代碼來源:JobExecutorTest.java

示例9: testExecuteWritesStderrToTheStderrListener

import java.util.concurrent.Semaphore; //導入方法依賴的package包/類
@Test
public void testExecuteWritesStderrToTheStderrListener() throws Throwable {
    final JobExecutor jobExecutor = getInstance();
    final String msgSuppliedToEcho = generateRandomString();
    final String bashArg = "echo " + msgSuppliedToEcho + " 1>&2"; // TODO: Naughty.
    final PersistedJob req =
            standardRequestWithCommand("bash", "-c", bashArg);
    final AtomicReference<byte[]> bytesEchoedToStderr = new AtomicReference<>(new byte[]{});
    final Subject<byte[]> stderrSubject = PublishSubject.create();

    stderrSubject.subscribe(bytes ->
            bytesEchoedToStderr.getAndUpdate(existingBytes ->
                    Bytes.concat(existingBytes, bytes)));

    final Semaphore s = new Semaphore(1);
    s.acquire();
    stderrSubject.doOnComplete(s::release).subscribe();

    final JobEventListeners listeners =
            createStderrListener(stderrSubject);

    jobExecutor.execute(req, listeners);

    s.tryAcquire(TestConstants.DEFAULT_TIMEOUT, MILLISECONDS);

    final String stringFromStderr = new String(bytesEchoedToStderr.get()).trim();
    assertThat(stringFromStderr).isEqualTo(msgSuppliedToEcho);
}
 
開發者ID:adamkewley,項目名稱:jobson,代碼行數:29,代碼來源:JobExecutorTest.java

示例10: main

import java.util.concurrent.Semaphore; //導入方法依賴的package包/類
public static void main(String[] args) throws Exception {
    for (Semaphore sem : new Semaphore[]{ new Semaphore(0),
                                          new Semaphore(0, false),
                                          new Semaphore(0, true)})
        for (int delay : new int[] {0, 1})
            for (int i = 0; i < 3; i++)
                if (sem.tryAcquire(delay, TimeUnit.MILLISECONDS))
                    throw new Error("Acquired Semaphore with no permits!");
    System.out.println("Done!");
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:11,代碼來源:TimedAcquire.java

示例11: handleWaitingForLog

import java.util.concurrent.Semaphore; //導入方法依賴的package包/類
private void handleWaitingForLog(String containerId, Semaphore ready) throws DockerException, InterruptedException {
    final LogStream logStream = dockerClient.logs(containerId,
            DockerClient.LogsParam.stdout(), DockerClient.LogsParam.stderr(), DockerClient.LogsParam.follow());

    LOGGER.debug("Waiting for log snippet '{}'", waitForLog);

    new Thread(() -> {
        try {
            while (logStream.hasNext()) {
                final LogMessage msg = logStream.next();

                final String logStr = StandardCharsets.UTF_8.decode(msg.content()).toString();
                LOGGER.debug("CONTAINER: {}", logStr);
                if (logStr.contains(waitForLog)) {
                    ready.release();
                    return;
                }
            }
        } finally {
            logStream.close();
        }
    }).start();

    if (!ready.tryAcquire(waitForLogTimeout, TimeUnit.MILLISECONDS)) {
        Assert.fail(String.format(
                "Did not observe desired Docker container log snippet within %d ms",
                waitForLogTimeout));
    }
}
 
開發者ID:itzg,項目名稱:junit-rule-docker,代碼行數:30,代碼來源:DockerRule.java

示例12: testSubmitJobEventListenersEchoStdoutWhenExecutorEchoesStdout

import java.util.concurrent.Semaphore; //導入方法依賴的package包/類
@Test
public void testSubmitJobEventListenersEchoStdoutWhenExecutorEchoesStdout() throws InterruptedException {
    final Subject<byte[]> stdoutSubject = ReplaySubject.create();
    final byte[] expectedStdoutBytes = generateRandomBytes();
    stdoutSubject.onNext(expectedStdoutBytes);

    final JobExecutor jobExecutor = MockJobExecutor.thatUses(stdoutSubject, Observable.never());
    final JobManager jobManager = createManagerWith(jobExecutor);

    final Semaphore s = new Semaphore(1);
    s.acquire();

    final JobEventListeners listeners = JobEventListeners.createStdoutListener(new Observer<byte[]>() {
        @Override
        public void onSubscribe(@NonNull Disposable disposable) {}

        @Override
        public void onNext(@NonNull byte[] bytes) {
            assertThat(bytes).isEqualTo(expectedStdoutBytes);
            s.release();
        }

        @Override
        public void onError(@NonNull Throwable throwable) {
            fail("Error from observable");
            s.release();
       }

        @Override
        public void onComplete() {}
    });

    jobManager.submit(STANDARD_VALID_REQUEST, listeners);

    if (!s.tryAcquire(1, SECONDS)) {
        fail("Timed out before any bytes received");
    }
}
 
開發者ID:adamkewley,項目名稱:jobson,代碼行數:39,代碼來源:JobManagerTest.java

示例13: waitFor

import java.util.concurrent.Semaphore; //導入方法依賴的package包/類
public static void waitFor(Semaphore semaphore, int count, long timeout, TimeUnit unit)
    throws InterruptedException {
  boolean success = semaphore.tryAcquire(count, timeout, unit);
  assertTrue("Operation timed out", success);
}
 
開發者ID:firebase,項目名稱:firebase-admin-java,代碼行數:6,代碼來源:TestHelpers.java

示例14: testSerializeDoesntLockDataNodeWhileWriting

import java.util.concurrent.Semaphore; //導入方法依賴的package包/類
@Test(timeout = 60000)
public void testSerializeDoesntLockDataNodeWhileWriting() throws Exception {
    DataTree tree = new DataTree();
    tree.createNode("/marker", new byte[] {42}, null, -1, 1, 1, 1);
    final DataNode markerNode = tree.getNode("/marker");
    final AtomicBoolean ranTestCase = new AtomicBoolean();
    DataOutputStream out = new DataOutputStream(new ByteArrayOutputStream());
    BinaryOutputArchive oa = new BinaryOutputArchive(out) {
        @Override
        public void writeRecord(Record r, String tag) throws IOException {
            // Need check if the record is a DataNode instance because of changes in ZOOKEEPER-2014
            // which adds default ACL to config node.
            if (r instanceof DataNode) {
                DataNode node = (DataNode) r;
                if (node.data.length == 1 && node.data[0] == 42) {
                    final Semaphore semaphore = new Semaphore(0);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            synchronized (markerNode) {
                                //When we lock markerNode, allow writeRecord to continue
                                semaphore.release();
                            }
                        }
                    }).start();

                    try {
                        boolean acquired = semaphore.tryAcquire(30, TimeUnit.SECONDS);
                        //This is the real assertion - could another thread lock
                        //the DataNode we're currently writing
                        Assert.assertTrue("Couldn't acquire a lock on the DataNode while we were calling tree.serialize", acquired);
                    } catch (InterruptedException e1) {
                        throw new RuntimeException(e1);
                    }
                    ranTestCase.set(true);
                }
            }

            super.writeRecord(r, tag);
        }
    };

    tree.serialize(oa, "test");

    //Let's make sure that we hit the code that ran the real assertion above
    Assert.assertTrue("Didn't find the expected node", ranTestCase.get());
}
 
開發者ID:didichuxing2,項目名稱:https-github.com-apache-zookeeper,代碼行數:48,代碼來源:DataTreeTest.java

示例15: testExecuteStatements

import java.util.concurrent.Semaphore; //導入方法依賴的package包/類
/** Test testExecuteStatements passes if no exceptions occur. */
public void testExecuteStatements() throws Exception {
    SQLHistoryManager testableManager = new SQLHistoryManager() {

        @Override
        protected FileObject getConfigRoot() {
            try {
                return FileUtil.toFileObject(getWorkDir());
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }

        @Override
        protected String getRelativeHistoryPath() {
            return "";
        }
        
    };
    // History does not yet exists as file
    assertNull(testableManager.getHistoryRoot(false));
    testableManager.getSQLHistory().add(new SQLHistoryEntry("jdbc:// mysql", "select * from TRAVEL.PERSON", Calendar.getInstance().getTime()));
    // History does not yet exists as file
    testableManager.save();
    assertNull(testableManager.getHistoryRoot(false));
    testableManager.getSQLHistory().add(new SQLHistoryEntry("jdbc:// oracle", "select * from PERSON", Calendar.getInstance().getTime()));
    final Semaphore s = new Semaphore(0);
    PropertyChangeListener releasingListener =
            new PropertyChangeListener() {
                @Override
                public void propertyChange(PropertyChangeEvent evt) {
                    if (SQLHistoryManager.PROP_SAVED.equals(
                            evt.getPropertyName())) {
                        s.release(); //release semaphore when data are saved
                    }
                }
            };
    testableManager.addPropertyChangeListener(releasingListener);
    testableManager.save();
    // History does not yet exists as file
    assertNull(testableManager.getHistoryRoot(false));
    // Enforce writing of history
    s.tryAcquire(6, TimeUnit.SECONDS);
    testableManager.removePropertyChangeListener(releasingListener);
    // History file need to exist now!
    assertNotNull(testableManager.getHistoryRoot(false));
    assertTrue(testableManager.getHistoryRoot(false).isData());
}
 
開發者ID:apache,項目名稱:incubator-netbeans,代碼行數:49,代碼來源:SQLHistoryPersistenceManagerTest.java


注:本文中的java.util.concurrent.Semaphore.tryAcquire方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。