Java Code Examples for java.util.concurrent.Semaphore#release()

The following examples show how to use java.util.concurrent.Semaphore#release() . 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: FileWatchServiceTest.java    From rocketmq with Apache License 2.0 6 votes vote down vote up
@Test
public void watchTwoFile_FileDeleted() throws Exception {
    File fileA = tempFolder.newFile();
    File fileB = tempFolder.newFile();
    final Semaphore waitSemaphore = new Semaphore(0);
    FileWatchService fileWatchService = new FileWatchService(
        new String[] {fileA.getAbsolutePath(), fileB.getAbsolutePath()},
        new FileWatchService.Listener() {
            @Override
            public void onChanged(String path) {
                waitSemaphore.release();
            }
        });
    fileWatchService.start();
    fileA.delete();
    boolean result = waitSemaphore.tryAcquire(1, 1000, TimeUnit.MILLISECONDS);
    assertThat(result).isFalse();
    modifyFile(fileB);
    result = waitSemaphore.tryAcquire(1, 1000, TimeUnit.MILLISECONDS);
    assertThat(result).isTrue();
    fileA.createNewFile();
    modifyFile(fileA);
    result = waitSemaphore.tryAcquire(1, 1000, TimeUnit.MILLISECONDS);
    assertThat(result).isTrue();
}
 
Example 2
Source File: TermServer.java    From termd with Apache License 2.0 6 votes vote down vote up
/**
 * Method returns once server is started.
 *
 * @throws InterruptedException
 */
public static TermServer start() throws InterruptedException {
  Semaphore mutex = new Semaphore(1);

  Runnable onStart = () -> {
    mutex.release();
  };
  TermServer termServer = new TermServer();

  serverThread = new Thread(() -> {
    try {
      termServer.start("localhost", 0, onStart);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  });
  mutex.acquire();
  serverThread.start();

  mutex.acquire();
  return termServer;
}
 
Example 3
Source File: FileWatchServiceTest.java    From rocketmq-4.3.0 with Apache License 2.0 6 votes vote down vote up
@Test
public void watchTwoFiles() throws Exception {
    File fileA = tempFolder.newFile();
    File fileB = tempFolder.newFile();
    final Semaphore waitSemaphore = new Semaphore(0);
    FileWatchService fileWatchService = new FileWatchService(
        new String[] {fileA.getAbsolutePath(), fileB.getAbsolutePath()},
        new FileWatchService.Listener() {
            @Override
            public void onChanged(String path) {
                waitSemaphore.release();
            }
        });
    fileWatchService.start();
    modifyFile(fileA);
    modifyFile(fileB);
    boolean result = waitSemaphore.tryAcquire(2, 1000, TimeUnit.MILLISECONDS);
    assertThat(result).isTrue();
}
 
Example 4
Source File: IOSSyslogListenerTest.java    From java-client with Apache License 2.0 6 votes vote down vote up
@Test
public void verifySyslogListenerCanBeAssigned() {
    final Semaphore messageSemaphore = new Semaphore(1);
    final Duration timeout = Duration.ofSeconds(15);

    driver.addSyslogMessagesListener((msg) -> messageSemaphore.release());
    driver.addSyslogConnectionListener(() -> System.out.println("Connected to the web socket"));
    driver.addSyslogDisconnectionListener(() -> System.out.println("Disconnected from the web socket"));
    driver.addSyslogErrorsListener(Throwable::printStackTrace);
    try {
        driver.startSyslogBroadcast();
        messageSemaphore.acquire();
        // This is needed for pushing some internal log messages
        driver.runAppInBackground(Duration.ofSeconds(1));
        assertTrue(String.format("Didn't receive any log message after %s timeout",
                DurationFormatUtils.formatDuration(timeout.toMillis(), "H:mm:ss", true)),
                messageSemaphore.tryAcquire(timeout.toMillis(), TimeUnit.MILLISECONDS));
    } catch (InterruptedException e) {
        throw new IllegalStateException(e);
    } finally {
        messageSemaphore.release();
        driver.stopSyslogBroadcast();
    }
}
 
Example 5
Source File: WorkThreadTrackingTaskTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
public void threadIsTrackedWhenComputing() throws InterruptedException {
  Semaphore assertBlocker = new Semaphore(0);
  Semaphore blocker = new Semaphore(0);
  WorkThreadTrackingTask<Object> task =
      new WorkThreadTrackingTask<>(
          () -> {
            try {
              assertBlocker.release();
              blocker.acquire();
            } catch (InterruptedException e) {
            }
            return null;
          });

  Thread thread =
      new Thread(
          () -> {
            task.compute();
          });
  thread.start();

  assertBlocker.acquire();
  assertEquals(thread, task.workThread);
  thread.interrupt();
}
 
Example 6
Source File: BackgroundThreadPosterTest.java    From thread-poster with Apache License 2.0 5 votes vote down vote up
@Test
public void execute_singleRunnable_executionSuccessful() throws Exception {
    // Arrange
    final Semaphore semaphore = new Semaphore(0);
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            semaphore.release();
        }
    };
    // Act
    SUT.post(runnable);
    // Assert
    semaphore.acquireUninterruptibly();
}
 
Example 7
Source File: CompletionStageBulkheadTest.java    From smallrye-fault-tolerance with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldLetMaxPlus1After1Left() throws Exception {
    Barrier delayBarrier = Barrier.noninterruptible();
    Semaphore letOneInSemaphore = new Semaphore(1);

    TestInvocation<CompletionStage<String>> invocation = TestInvocation.delayed(delayBarrier,
            () -> {
                letOneInSemaphore.acquire();
                return CompletableFuture.completedFuture("shouldLetMaxPlus1After1Left");
            });
    CompletionStageBulkhead<String> bulkhead = bulkhead(invocation, "shouldLetMaxPlus1After1Left", 2, 3);

    List<TestThread<CompletionStage<String>>> threads = new ArrayList<>();

    for (int i = 0; i < 5; i++) {
        threads.add(TestThread.runOnTestThread(bulkhead));
    }
    delayBarrier.open();
    TestThread<CompletionStage<String>> finishedThread = getSingleFinishedThread(threads, 1000);
    threads.remove(finishedThread);

    assertThat(finishedThread.await().toCompletableFuture().get()).isEqualTo("shouldLetMaxPlus1After1Left");

    threads.add(TestThread.runOnTestThread(bulkhead));
    letOneInSemaphore.release(100);
    delayBarrier.open();
    for (TestThread<CompletionStage<String>> thread : threads) {
        CompletionStage<String> result = thread.await();
        assertThat(result.toCompletableFuture().join()).isEqualTo("shouldLetMaxPlus1After1Left");
    }
}
 
Example 8
Source File: LocalHistoryStoreImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void fileDeleteFromMove(VCSFileProxy from, VCSFileProxy to, long ts) {
    Semaphore s = lock(from, "fileDeleteFromMove"); // NOI18N
    try {
        fileDeleteImpl(from, FileUtils.getPath(from), FileUtils.getPath(to), ts);
    } catch (IOException ioe) {
        LocalHistory.LOG.log(Level.WARNING, null, ioe);
    } finally {
        if(s != null) s.release();
    }
    fireChanged(from, ts);
}
 
Example 9
Source File: MySemaphore.java    From ThreadProject with MIT License 5 votes vote down vote up
public static void main(String args[]){
    ExecutorService list=Executors.newCachedThreadPool();
    Semaphore position=new Semaphore(2);
    for(int i=0;i<10;i++){
     list.submit(new MySemaphore(i+1,position));
    }
    list.shutdown();
    position.acquireUninterruptibly(2);
    System.out.println("使用完毕,需要清扫了");
    position.release(2);
}
 
Example 10
Source File: SemaphoreTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public void testReleaseAcquireSameThread(boolean fair,
                                         final AcquireMethod acquirer) {
    Semaphore s = new Semaphore(1, fair);
    for (int i = 1; i < 6; i++) {
        s.release(i);
        assertEquals(1 + i, s.availablePermits());
        try {
            acquirer.acquire(s, i);
        } catch (InterruptedException e) { threadUnexpectedException(e); }
        assertEquals(1, s.availablePermits());
    }
}
 
Example 11
Source File: Drpc.java    From jstorm with Apache License 2.0 5 votes vote down vote up
@Override
public void failRequest(String id) throws TException {
    Semaphore sem = this.idToSem.get(id);
    LOG.info("failRequest result  for id " + id + " at " + (System.currentTimeMillis()));
    if (sem != null) {
        this.idToResult.put(id, new DRPCExecutionException("Request failed"));
        sem.release();
    }
}
 
Example 12
Source File: SemaphoreDemo.java    From JavaCommon with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    // 线程池
    ExecutorService exec = Executors.newCachedThreadPool();
    // 只能5个线程同时访问
    final Semaphore semaphore = new Semaphore(5);
    // 模拟20个客户端访问
    for (int index = 0; index < 20; index++) {
        final int NO = index;
        Runnable run = new Runnable() {

            public void run() {
                try {
                    // 获取许可
                    semaphore.acquire();
                    System.out.println("Accessing: " + NO);
                    Thread.sleep((long) (Math.random() * 10000));
                    // 访问完后,释放
                    semaphore.release();
                    System.out.println("-----------------" + semaphore.availablePermits());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        };
        exec.execute(run);
    }
    // 退出线程池
    exec.shutdown();
}
 
Example 13
Source File: PaymentRestHacksControllerV4.java    From flowing-retail with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(JobClient client, ActivatedJob job) throws Exception {
     String traceId = (String) job.getVariablesAsMap().get("traceId");
     Semaphore s = semaphors.get(traceId);
     if (s!=null) {
       s.release();
       semaphors.remove(traceId);
     }
     client.newCompleteCommand(job.getKey()).send().join();
   }
 
Example 14
Source File: RemoteRepositoriesSemaphore.java    From snap-desktop with GNU General Public License v3.0 4 votes vote down vote up
public void releasePermission(String remoteRepositoryName, Credentials credentials) throws InterruptedException {
    Semaphore semaphore = getSemaphore(remoteRepositoryName, credentials);
    if (semaphore != null) {
        semaphore.release(1);
    }
}
 
Example 15
Source File: TestEnsurePath.java    From curator with Apache License 2.0 4 votes vote down vote up
@Test
public void    testSimultaneous() throws Exception
{
    ZooKeeper               client = mock(ZooKeeper.class, Mockito.RETURNS_MOCKS);
    RetryPolicy             retryPolicy = new RetryOneTime(1);
    RetryLoop               retryLoop = new RetryLoopImpl(retryPolicy, null);
    final CuratorZookeeperClient  curator = mock(CuratorZookeeperClient.class);
    when(curator.getZooKeeper()).thenReturn(client);
    when(curator.getRetryPolicy()).thenReturn(retryPolicy);
    when(curator.newRetryLoop()).thenReturn(retryLoop);

    final Stat              fakeStat = mock(Stat.class);
    final CountDownLatch    startedLatch = new CountDownLatch(2);
    final CountDownLatch    finishedLatch = new CountDownLatch(2);
    final Semaphore         semaphore = new Semaphore(0);
    when(client.exists(Mockito.<String>any(), anyBoolean())).thenAnswer
    (
        new Answer<Stat>()
        {
            @Override
            public Stat answer(InvocationOnMock invocation) throws Throwable
            {
                semaphore.acquire();
                return fakeStat;
            }
        }
    );

    final EnsurePath    ensurePath = new EnsurePath("/one/two/three");
    ExecutorService     service = Executors.newCachedThreadPool();
    for ( int i = 0; i < 2; ++i )
    {
        service.submit
        (
            new Callable<Void>()
            {
                @Override
                public Void call() throws Exception
                {
                    startedLatch.countDown();
                    ensurePath.ensure(curator);
                    finishedLatch.countDown();
                    return null;
                }
            }
        );
    }

    Assert.assertTrue(startedLatch.await(10, TimeUnit.SECONDS));
    semaphore.release(3);
    Assert.assertTrue(finishedLatch.await(10, TimeUnit.SECONDS));
    verify(client, times(3)).exists(Mockito.<String>any(), anyBoolean());

    ensurePath.ensure(curator);
    verifyNoMoreInteractions(client);
    ensurePath.ensure(curator);
    verifyNoMoreInteractions(client);
}
 
Example 16
Source File: GuardedProcess.java    From Maying with Apache License 2.0 4 votes vote down vote up
public GuardedProcess start(final RestartCallback onRestartCallback) throws InterruptedException {
    final Semaphore semaphore = new Semaphore(1);
    semaphore.acquire();

    guardThread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                RestartCallback callback = null;
                while (!isDestroyed) {
                    VayLog.i(TAG, "start process: " + cmd);
                    long startTime = System.currentTimeMillis();

                    process = new ProcessBuilder(cmd).redirectErrorStream(true).start();

                    InputStream is = process.getInputStream();
                    new StreamLogger(is, TAG).start();

                    if (callback == null) {
                        callback = onRestartCallback;
                    } else {
                        callback.onRestart();
                    }

                    semaphore.release();
                    process.waitFor();

                    synchronized (this) {
                        if (isRestart) {
                            isRestart = false;
                        } else {
                            if (System.currentTimeMillis() - startTime < 1000) {
                                Log.w(TAG, "process exit too fast, stop guard: " + cmd);
                                isDestroyed = true;
                            }
                        }
                    }

                }
            } catch (Exception ignored) {
                VayLog.i(TAG, "thread interrupt, destroy process: " + cmd);
                if (process!=null) {
                    process.destroy();
                }
            } finally {
                semaphore.release();
            }
        }
    }, "GuardThread-" + cmd);

    guardThread.start();
    semaphore.acquire();
    return this;
}
 
Example 17
Source File: RealtimeTest.java    From firebase-android-sdk with Apache License 2.0 4 votes vote down vote up
@Test
public void testOnDisconnectWithServerValuesWorks()
    throws TestFailure, TimeoutException, DatabaseException, InterruptedException {
  List<DatabaseReference> refs = IntegrationTestHelpers.getRandomNode(1);
  DatabaseReference writer = refs.get(0);
  final DatabaseConfig ctx = IntegrationTestHelpers.getContext(0);
  RepoManager.resume(ctx);

  final Semaphore opSemaphore = new Semaphore(0);
  final Semaphore valSemaphore = new Semaphore(0);
  ReadFuture writerFuture =
      new ReadFuture(
          writer,
          new ReadFuture.CompletionCondition() {
            @Override
            public boolean isComplete(List<EventRecord> events) {
              valSemaphore.release();
              Object snapVal = events.get(events.size() - 1).getSnapshot().getValue();
              return snapVal != null;
            }
          });

  // Wait for initial (null) value.
  IntegrationTestHelpers.waitFor(valSemaphore);

  Map<String, Object> initialValues =
      new MapBuilder()
          .put("a", ServerValue.TIMESTAMP)
          .put(
              "b",
              new MapBuilder()
                  .put(".value", ServerValue.TIMESTAMP)
                  .put(".priority", ServerValue.TIMESTAMP)
                  .build())
          .build();

  writer
      .onDisconnect()
      .setValue(
          initialValues,
          ServerValue.TIMESTAMP,
          new DatabaseReference.CompletionListener() {
            @Override
            public void onComplete(DatabaseError error, DatabaseReference ref) {
              RepoManager.interrupt(ctx);
              opSemaphore.release();
            }
          });
  IntegrationTestHelpers.waitFor(opSemaphore);

  EventRecord readerEventRecord = writerFuture.timedGet().get(1);
  DataSnapshot snap = readerEventRecord.getSnapshot();

  RepoManager.resume(ctx);

  assertEquals(snap.child("a").getValue().getClass(), Long.class);
  assertEquals(snap.getPriority().getClass(), Double.class);
  assertEquals(snap.getPriority(), snap.child("b").getPriority());
  assertEquals(snap.child("a").getValue(), snap.child("b").getValue());
  long drift = System.currentTimeMillis() - Long.parseLong(snap.child("a").getValue().toString());
  assertThat(Math.abs(drift), lessThan(2000l));
}
 
Example 18
Source File: TestRecovery.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Test
public void testTruncatedLog() throws Exception {
  try {
    TestInjection.skipIndexWriterCommitOnClose = true;
    final Semaphore logReplay = new Semaphore(0);
    final Semaphore logReplayFinish = new Semaphore(0);

    UpdateLog.testing_logReplayHook = () -> {
      try {
        assertTrue(logReplay.tryAcquire(timeout, TimeUnit.SECONDS));
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    };

    UpdateLog.testing_logReplayFinishHook = () -> logReplayFinish.release();

    UpdateLog ulog = h.getCore().getUpdateHandler().getUpdateLog();
    File logDir = new File(h.getCore().getUpdateHandler().getUpdateLog().getLogDir());

    clearIndex();
    assertU(commit());

    assertU(adoc("id","F1"));
    assertU(adoc("id","F2"));
    assertU(adoc("id","F3"));

    h.close();
    String[] files = ulog.getLogList(logDir);
    Arrays.sort(files);
    try (RandomAccessFile raf = new RandomAccessFile(new File(logDir, files[files.length - 1]), "rw")) {
      raf.seek(raf.length());  // seek to end
      raf.writeLong(0xffffffffffffffffL);
      raf.writeChars("This should be appended to a good log file, representing a bad partially written record.");
    }

    logReplay.release(1000);
    logReplayFinish.drainPermits();
    ignoreException("OutOfBoundsException");  // this is what the corrupted log currently produces... subject to change.
    createCore();
    assertTrue(logReplayFinish.tryAcquire(timeout, TimeUnit.SECONDS));
    resetExceptionIgnores();
    assertJQ(req("q","*:*") ,"/response/numFound==3");

    //
    // Now test that the bad log file doesn't mess up retrieving latest versions
    //

    String v104 = getNextVersion();
    String v105 = getNextVersion();
    String v106 = getNextVersion();
    
    updateJ(jsonAdd(sdoc("id","F4", "_version_",v104)), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));
    updateJ(jsonAdd(sdoc("id","F5", "_version_",v105)), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));
    updateJ(jsonAdd(sdoc("id","F6", "_version_",v106)), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));

    // This currently skips the bad log file and also returns the version of the clearIndex (del *:*)
    // assertJQ(req("qt","/get", "getVersions","6"), "/versions==[106,105,104]");
    assertJQ(req("qt","/get", "getVersions","3"), "/versions==["+v106+","+v105+","+v104+"]");

  } finally {
    UpdateLog.testing_logReplayHook = null;
    UpdateLog.testing_logReplayFinishHook = null;
  }
}
 
Example 19
Source File: RealtimeTestIT.java    From firebase-admin-java with Apache License 2.0 4 votes vote down vote up
@Test
public void testOnDisconnectWithServerValuesWorks()
    throws TestFailure, TimeoutException, InterruptedException {
  List<DatabaseReference> refs = IntegrationTestUtils.getRandomNode(masterApp, 1);
  DatabaseReference writer = refs.get(0);
  final DatabaseConfig ctx = TestHelpers.getDatabaseConfig(masterApp);
  RepoManager.resume(ctx);

  final Semaphore opSemaphore = new Semaphore(0);
  final Semaphore valSemaphore = new Semaphore(0);
  final ReadFuture writerFuture = new ReadFuture(writer, new ReadFuture.CompletionCondition() {
    @Override
    public boolean isComplete(List<EventRecord> events) {
      valSemaphore.release();
      Object snapVal = events.get(events.size() - 1).getSnapshot().getValue();
      return snapVal != null;
    }
  });

  // Wait for initial (null) value.
  TestHelpers.waitFor(valSemaphore);

  Map<String, Object> initialValues = new MapBuilder()
      .put("a", ServerValue.TIMESTAMP).put("b", new MapBuilder()
          .put(".value", ServerValue.TIMESTAMP).put(".priority", ServerValue.TIMESTAMP).build())
      .build();

  writer.onDisconnect().setValue(initialValues, ServerValue.TIMESTAMP,
      new DatabaseReference.CompletionListener() {
        @Override
        public void onComplete(DatabaseError error, DatabaseReference ref) {
          RepoManager.interrupt(ctx);
          opSemaphore.release();
        }
      });
  TestHelpers.waitFor(opSemaphore);

  EventRecord readerEventRecord = writerFuture.timedGet().get(1);
  DataSnapshot snap = readerEventRecord.getSnapshot();

  RepoManager.resume(ctx);

  assertEquals(snap.child("a").getValue().getClass(), Long.class);
  assertEquals(snap.getPriority().getClass(), Double.class);
  assertEquals(snap.getPriority(), snap.child("b").getPriority());
  assertEquals(snap.child("a").getValue(), snap.child("b").getValue());
  TestHelpers.assertTimeDelta(Long.parseLong(snap.child("a").getValue().toString()));
}
 
Example 20
Source File: TestServiceDiscovery.java    From xian with Apache License 2.0 4 votes vote down vote up
@Test
public void testCrashedServerMultiInstances() throws Exception
{
    List<Closeable> closeables = Lists.newArrayList();
    try
    {
        Timing timing = new Timing();
        CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));
        closeables.add(client);
        client.start();

        final Semaphore semaphore = new Semaphore(0);
        ServiceInstance<String> instance1 = ServiceInstance.<String>builder().payload("thing").name("test").port(10064).build();
        ServiceInstance<String> instance2 = ServiceInstance.<String>builder().payload("thing").name("test").port(10065).build();
        ServiceDiscovery<String> discovery = new ServiceDiscoveryImpl<String>(client, "/test", new JsonInstanceSerializer<String>(String.class),new FastjsonServiceDefinitionSerializer<>(String.class), instance1, false)
        {
            @Override
            protected void internalRegisterService(ServiceInstance<String> service) throws Exception
            {
                super.internalRegisterService(service);
                semaphore.release();
            }
        };
        closeables.add(discovery);
        discovery.start();
        discovery.registerService(instance2);

        timing.acquireSemaphore(semaphore, 2);
        Assert.assertEquals(discovery.queryForInstances("test").size(), 2);

        KillSession.kill(client.getZookeeperClient().getZooKeeper(), server.getConnectString());
        server.stop();

        server.restart();
        closeables.add(server);

        timing.acquireSemaphore(semaphore, 2);
        Assert.assertEquals(discovery.queryForInstances("test").size(), 2);
    }
    finally
    {
        for ( Closeable c : closeables )
        {
            CloseableUtils.closeQuietly(c);
        }
    }
}