java.util.concurrent.Semaphore Java Examples

The following examples show how to use java.util.concurrent.Semaphore. 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: CheckedLockLoops.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
final int loop(int n) {
    final Semaphore sem = this.sem;
    int sum = 0;
    int x = 0;
    while (n-- > 0) {
        sem.acquireUninterruptibly();
        try {
            x = setValue(LoopHelpers.compute1(getValue()));
        }
        finally {
            sem.release();
        }
        sum += LoopHelpers.compute2(x);
    }
    return sum;
}
 
Example #2
Source File: VectorExample1.java    From Project with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    ExecutorService executorService = Executors.newCachedThreadPool();
    final Semaphore semaphore = new Semaphore(threadTotal);
    final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
    for (int i = 0; i < clientTotal; i++) {
        final int count = i;
        executorService.execute(() -> {
            try {
                semaphore.acquire();
                update(count);
                semaphore.release();
            } catch (Exception e) {
                log.error("exception", e);
            }
            countDownLatch.countDown();
        });
    }
    countDownLatch.await();
    executorService.shutdown();
    log.info("size:{}", list.size());
}
 
Example #3
Source File: DataTestIT.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testSetPriorityOnNonexistentNode() throws InterruptedException {
  final DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp);

  final Semaphore semaphore = new Semaphore(0);
  ref.setPriority(1, new DatabaseReference.CompletionListener() {
    @Override
    public void onComplete(DatabaseError error, DatabaseReference callbackRef) {
      assertEquals(ref, callbackRef);
      assertNotNull(error);
      semaphore.release(1);
    }
  });

  assertTrue(semaphore.tryAcquire(1, TestUtils.TEST_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS));
}
 
Example #4
Source File: ApolloMockServerApiTest.java    From apollo with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdateSamePropertyTwice() throws Exception {
  String someNewValue = "someNewValue";

  Config otherConfig = ConfigService.getConfig(anotherNamespace);

  final Semaphore changes = new Semaphore(0);

  otherConfig.addChangeListener(new ConfigChangeListener() {
    @Override
    public void onChange(ConfigChangeEvent changeEvent) {
      changes.release();
    }
  });

  assertEquals("otherValue3", otherConfig.getProperty("key3", null));

  embeddedApollo.addOrModifyProperty(anotherNamespace, "key3", someNewValue);
  embeddedApollo.addOrModifyProperty(anotherNamespace, "key3", someNewValue);

  assertTrue(changes.tryAcquire(5, TimeUnit.SECONDS));
  assertEquals(someNewValue, otherConfig.getProperty("key3", null));
  assertEquals(0, changes.availablePermits());
}
 
Example #5
Source File: RegexSpeedTest.java    From logsniffer with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testPar() throws InterruptedException {
	for (int z = 0; z < 2; z++) {
		parPos = 0;
		final int parCount = 4;
		final Semaphore s = new Semaphore(parCount);
		final long start = System.currentTimeMillis();
		for (int i = 0; i < parCount; i++) {
			final Parser parser = new Parser(s);
			parser.start();
		}
		s.acquire(parCount);
		final long time = System.currentTimeMillis() - start;
		System.out.println("Finished parallel " + size + " in " + time + " => " + Math.round(size / time * 1000));
	}
}
 
Example #6
Source File: BandedUpdaterTest.java    From jelectrum with MIT License 6 votes vote down vote up
@Test
public void multiThreadTest()
    throws Exception
{
    TreeMap<String, HashSet<String> > map=new DelayMap<String, HashSet<String>>();

    BandedUpdater<String, String> bu = new BandedUpdater<String,String>(map,16);
    Semaphore sem = new Semaphore(0);

    for(int i=0; i<100; i++)
    {
        new InsertThread(bu, sem).start();
    }
    sem.acquire(100);

    Assert.assertEquals(1, map.size());
    Assert.assertEquals(1000, map.get("a").size());

    
}
 
Example #7
Source File: PerformanceBenchmarks.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
private static void addChildrenAndWait(DatabaseReference reference, int amount)
    throws InterruptedException {
  addChildren(reference, amount, 0);
  final Semaphore semaphore = new Semaphore(0);
  reference
      .child("k-" + amount)
      .setValue(
          "last-value",
          new DatabaseReference.CompletionListener() {
            @Override
            public void onComplete(DatabaseError error, DatabaseReference ref) {
              semaphore.release();
            }
          });
  Assert.assertTrue(semaphore.tryAcquire(60, TimeUnit.SECONDS));
}
 
Example #8
Source File: FileWatchServiceTest.java    From rocketmq-4.3.0 with Apache License 2.0 6 votes vote down vote up
@Test
public void watchSingleFile() throws Exception {
    final File file = tempFolder.newFile();
    final Semaphore waitSemaphore = new Semaphore(0);
    FileWatchService fileWatchService = new FileWatchService(new String[] {file.getAbsolutePath()}, new FileWatchService.Listener() {
        @Override
        public void onChanged(String path) {
            assertThat(file.getAbsolutePath()).isEqualTo(path);
            waitSemaphore.release();
        }
    });
    fileWatchService.start();
    modifyFile(file);
    boolean result = waitSemaphore.tryAcquire(1, 1000, TimeUnit.MILLISECONDS);
    assertThat(result).isTrue();
}
 
Example #9
Source File: AtomicExample6.java    From Project with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    ExecutorService executorService = Executors.newCachedThreadPool();
    final Semaphore semaphore = new Semaphore(threadTotal);
    final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
    for (int i = 0; i < clientTotal ; i++) {
        executorService.execute(() -> {
            try {
                semaphore.acquire();
                test();
                semaphore.release();
            } catch (Exception e) {
                log.error("exception", e);
            }
            countDownLatch.countDown();
        });
    }
    countDownLatch.await();
    executorService.shutdown();
    log.info("isHappened:{}", isHappened.get());
}
 
Example #10
Source File: CountExample2.java    From Project with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    ExecutorService executorService = Executors.newCachedThreadPool();
    //Semaphore和CountDownLatch模拟并发
    final Semaphore semaphore = new Semaphore(threadTotal);
    final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
    for (int i = 0; i < clientTotal ; i++) {
        executorService.execute(() -> {
            try {
                semaphore.acquire();
                add();
                semaphore.release();
            } catch (Exception e) {
                log.error("exception", e);
            }
            countDownLatch.countDown();
        });
    }
    countDownLatch.await();
    executorService.shutdown();
    log.info("count:{}", count.get());
}
 
Example #11
Source File: GetGraphImage.java    From constellation with Apache License 2.0 6 votes vote down vote up
@Override
public void callService(final PluginParameters parameters, final InputStream in, final OutputStream out) throws IOException {
    final Graph graph = GraphManager.getDefault().getActiveGraph();

    // This is asynchronous, so we need a Semaphore.
    //
    final GraphNode graphNode = GraphNode.getGraphNode(graph);
    final VisualManager visualManager = graphNode.getVisualManager();
    final BufferedImage[] img1 = new BufferedImage[1];

    if (visualManager != null) {
        final Semaphore waiter = new Semaphore(0);
        visualManager.exportToBufferedImage(img1, waiter);
        waiter.acquireUninterruptibly();

        ImageIO.write(img1[0], "png", out);
    } else {
        throw new IOException("Graph image unavailable");
    }
}
 
Example #12
Source File: CollectionsExample1.java    From Project with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    ExecutorService executorService = Executors.newCachedThreadPool();
    final Semaphore semaphore = new Semaphore(threadTotal);
    final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
    for (int i = 0; i < clientTotal; i++) {
        final int count = i;
        executorService.execute(() -> {
            try {
                semaphore.acquire();
                update(count);
                semaphore.release();
            } catch (Exception e) {
                log.error("exception", e);
            }
            countDownLatch.countDown();
        });
    }
    countDownLatch.await();
    executorService.shutdown();
    log.info("size:{}", list.size());
}
 
Example #13
Source File: ZKDistributedDelayLock.java    From zkclient with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @param timeout
 * @param delayTimeMillis
 * @return 
 * @return boolean
 */
public boolean lock(int timeout,int delayTimeMillis){
    this.delayTimeMillis.set(delayTimeMillis);
    long startTime = System.currentTimeMillis();
    while (true) {
        try {
          //信号量为0,线程就会一直等待直到数据变成正数
            semaphore = new Semaphore(0);
            client.create(lockPath+"/lock", lockNodeData, CreateMode.EPHEMERAL);
            hasLock.set(true);
            return true;
        } catch (ZKNodeExistsException e) {
            try {
                 semaphore.acquire();
            } catch (InterruptedException interruptedException) {
                return false;
            }
        }
        //超时处理
        if (timeout > 0 && (System.currentTimeMillis() - startTime) >= timeout) {
            return false;
        }
    }
}
 
Example #14
Source File: IntegrationTestHelpers.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
public static void waitForEvents(DatabaseReference ref) {
  try {
    // Make sure queue is done and all events are queued
    IntegrationTestHelpers.waitForQueue(ref);
    // Next, all events were queued, make sure all events are done raised
    final Semaphore semaphore = new Semaphore(0);
    ref.getRepo()
        .postEvent(
            new Runnable() {
              @Override
              public void run() {
                semaphore.release();
              }
            });
    semaphore.acquire();
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
 
Example #15
Source File: RaceTest.java    From Intra with Apache License 2.0 6 votes vote down vote up
@Test
public void Success() throws Exception {
  final int N = 7;
  String[] urls = new String[N];
  Semaphore done = new Semaphore(0);
  Race.start(new SuccessProber(), urls, (int index) -> {
    assertTrue(index >= 0);
    assertTrue(index < N);
    done.release();
    if (done.availablePermits() > 1) {
      // Multiple success callbacks.
      fail();
    }
  });
  // Wait for listener to run.
  done.acquire();
}
 
Example #16
Source File: ImageLoader.java    From LLApp with Apache License 2.0 6 votes vote down vote up
/**
 * 初始化
 * 
 * @param threadCount
 * @param type
 */
private void init(int threadCount, Type type,Context context)
{
	// 获取我们应用的最大可用内存
	int maxMemory = (int) Runtime.getRuntime().maxMemory();
	int cacheMemory = maxMemory / 8;
	//注意此处要获取全局Context,避免引用Activity造成资源无法释放
	mContext=context.getApplicationContext();
	mLruCache = new LruCache<String, Bitmap>(cacheMemory){
		@Override
		protected int sizeOf(String key, Bitmap value)
		{
			//				return value.getAllocationByteCount();
			return value.getRowBytes() * value.getHeight(); //旧版本方法
		}

	};

	// 创建线程池
	mThreadPool = Executors.newFixedThreadPool(threadCount);
	mType = type;
	mSemaphoreThreadPool = new Semaphore(threadCount,true);
	mTaskQueue = new LinkedBlockingDeque<Runnable>();	
	initBackThread();
}
 
Example #17
Source File: summaryEvaluator.java    From Ngram-Graphs with Apache License 2.0 6 votes vote down vote up
/** TODO */
public CalcSimilRunner(int iWordNGramSize_Min, int iWordNGramSize_Max, int iWord_Dmax,
        int iCharacterNGramSize_Min, int iCharacterNGramSize_Max, int iCharacter_Dmax,
        CategorizedFileEntry cfeCurEntry, List lCompareAgainst, Semaphore sSem, 
        boolean dDoCharNGrams, boolean dDoWordNGrams, PrintStream psOutStream,
        boolean bSilent, summaryEvaluator seCaller, int iWeightingMethod,
        boolean bProgress) {
    WordNGramSize_Min = iWordNGramSize_Min;
    WordNGramSize_Max = iWordNGramSize_Max;
    Word_Dmax = iWord_Dmax;
    CharacterNGramSize_Min = iCharacterNGramSize_Min;
    CharacterNGramSize_Max = iCharacterNGramSize_Max;
    Character_Dmax = iCharacter_Dmax;        
    CurEntry = cfeCurEntry;
    CompareAgainst = lCompareAgainst;
    Sem = sSem;
    DoCharNGrams = dDoCharNGrams;
    DoWordNGrams = dDoWordNGrams;
    OutStream = psOutStream;
    Silent = bSilent;
    Caller = seCaller;
    WeightingMethod = iWeightingMethod;
    Progress = bProgress;
}
 
Example #18
Source File: summaryGenericEvaluator.java    From Ngram-Graphs with Apache License 2.0 6 votes vote down vote up
public GenericCalcSimilRunner(int iNGramSize_Min, int iNGramSize_Max, int iDmax,
        CategorizedFileEntry cfeCurEntry, List lCompareAgainst, Semaphore sSem, 
        PrintStream psOutStream, boolean bSilent, summaryGenericEvaluator seCaller, 
        String sDocumentClass, String sComparatorClass,
        boolean bProgress) {
    NGramSize_Min = iNGramSize_Min;
    NGramSize_Max = iNGramSize_Max;
    Dmax = iDmax;        
    CurEntry = cfeCurEntry;
    CompareAgainst = lCompareAgainst;
    Sem = sSem;
    OutStream = psOutStream;
    Silent = bSilent;
    Caller = seCaller;
    Progress = bProgress;
    DocumentClass = sDocumentClass;
    ComparatorClass = sComparatorClass;
}
 
Example #19
Source File: GridCacheDatabaseSharedManager.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @param consumer Runnable task.
 * @param grpId Group Id.
 * @param partId Partition Id.
 * @param exec Striped executor.
 */
public void stripedApplyPage(
    Consumer<PageMemoryEx> consumer,
    int grpId,
    int partId,
    StripedExecutor exec,
    Semaphore semaphore
) throws IgniteCheckedException {
    assert consumer != null;
    assert exec != null;
    assert semaphore != null;

    PageMemoryEx pageMem = getPageMemoryForCacheGroup(grpId);

    if (pageMem == null)
        return;

    stripedApply(() -> consumer.accept(pageMem), grpId, partId, exec, semaphore);
}
 
Example #20
Source File: ProjectBuilder.java    From pnc with Apache License 2.0 5 votes vote down vote up
private Semaphore registerReleaseListenersAndAcquireSemaphore(
        Consumer<BuildStatusChangedEvent> onStatusUpdate,
        int nStatusUpdates) throws InterruptedException {

    final Semaphore semaphore = new Semaphore(nStatusUpdates);
    statusChangedReceiver.addBuildStatusChangedEventListener(statusUpdate -> {
        log.debug("Received status update {}.", statusUpdate.toString());
        onStatusUpdate.accept(statusUpdate);
        semaphore.release(1);
        log.debug("Semaphore released, there are {} free entries", semaphore.availablePermits());
    });
    semaphore.acquire(nStatusUpdates);
    return semaphore;
}
 
Example #21
Source File: SSLFacadeTest.java    From sslfacade with MIT License 5 votes vote down vote up
public void attachHandshakeListener(final String who, final ISSLFacade ssl, final List<String> notifications, final Semaphore sem)
{
  ssl.setHandshakeCompletedListener(new IHandshakeCompletedListener()
  {
    @Override
    public void onComplete()
    {
      log(who + ": Handshake completed.");
      notifications.add(END_OF_HANDSHAKE);
      sem.release();
      log(who + ": semaphore released " + sem);
    }
  });
}
 
Example #22
Source File: PartitionedScheduledExecutorTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testRunningJobsAreInterruptedAfterShutdownNow() throws InterruptedException {
  final int jobCount = 4;

  ExecutorService worker = Executors.newCachedThreadPool();
  try {
    PartitionedScheduledExecutor executor = new PartitionedScheduledExecutor(scheduler, worker);

    final Semaphore jobSemaphore = new Semaphore(0);
    final Semaphore testSemaphore = new Semaphore(0);
    final AtomicInteger interrupted = new AtomicInteger();

    for (int i = 0; i < jobCount; i++) {
      executor.submit(() -> {
        testSemaphore.release();
        try {
          jobSemaphore.acquire();
        } catch (InterruptedException e) {
          interrupted.incrementAndGet();
        }
      });
    }

    testSemaphore.acquireUninterruptibly(jobCount);

    assertThat(executor.shutdownNow(), empty());
    assertThat(executor.awaitTermination(2, MINUTES), is(true));
    assertThat(executor.isShutdown(), is(true));
    assertThat(executor.isTerminated(), is(true));

    assertThat(jobSemaphore.availablePermits(), is(0));
    assertThat(interrupted.get(), is(jobCount));
  } finally {
    worker.shutdown();
  }
}
 
Example #23
Source File: DataTestIT.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testPriorityUpdate() throws InterruptedException {
  List<DatabaseReference> refs = IntegrationTestUtils.getRandomNode(masterApp, 2);
  final DatabaseReference writer = refs.get(0);
  final DatabaseReference reader = refs.get(1);

  Map<String, Object> writeValue = new MapBuilder().put("a", 5).put(".priority", "pri1").build();

  Map<String, Object> updateValue = new MapBuilder().put("a", 6).put(".priority", "pri2")
      .put("b", new MapBuilder().put(".priority", "pri3").put("c", 10).build()).build();

  final Semaphore semaphore = new Semaphore(0);
  writer.setValueAsync(writeValue);
  writer.updateChildren(updateValue, new DatabaseReference.CompletionListener() {
    @Override
    public void onComplete(DatabaseError error, DatabaseReference ref) {
      assertNull(error);
      semaphore.release(1);
    }
  });
  TestHelpers.waitFor(semaphore);

  DataSnapshot snap = TestHelpers.getSnap(reader);
  assertEquals(6L, snap.child("a").getValue());
  assertEquals("pri2", snap.getPriority());
  assertEquals("pri3", snap.child("b").getPriority());
  assertEquals(10L, snap.child("b/c").getValue());
}
 
Example #24
Source File: QueryTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void staleItemsRemovedFromTheCache()
    throws InterruptedException, TestFailure, TimeoutException {
  List<DatabaseReference> refs = IntegrationTestHelpers.getRandomNode(2);
  DatabaseReference reader = refs.get(0);
  DatabaseReference writer = refs.get(1);

  final AtomicBoolean startChecking = new AtomicBoolean(false);
  final Semaphore ready = new Semaphore(0);
  ReadFuture future =
      new ReadFuture(
          reader.limitToLast(2),
          new ReadFuture.CompletionCondition() {
            @Override
            public boolean isComplete(List<EventRecord> events) {
              DataSnapshot snap = events.get(events.size() - 1).getSnapshot();
              Object result = snap.getValue();
              if (startChecking.compareAndSet(false, true) && result == null) {
                ready.release(1);
                return false;
              }
              // We already initialized the location, and now the remove has happened so that we
              // have no more data
              return startChecking.get() && result == null;
            }
          });

  IntegrationTestHelpers.waitFor(ready);
  for (int i = 0; i < 4; ++i) {
    writer.child("k" + i).setValue(i);
  }

  writer.removeValue();
  future.timedGet();
}
 
Example #25
Source File: SubscriptionWorker.java    From sourcerer with MIT License 5 votes vote down vote up
public SubscriptionWorker(
        final EventRepository<T> repository,
        final EventSubscriptionPositionSource positionSource,
        final EventSubscriptionHandler<T> handler,
        final SubscriptionWorkerConfig config) {
    this.repository = repository;
    this.positionSource = positionSource;
    this.handler = handler;
    this.config = config;
    this.cancelled = new AtomicBoolean(false);
    this.retryCount = new AtomicInteger(0);
    this.sleeper = new Semaphore(0);
}
 
Example #26
Source File: ZonkyPostgresDatabaseProvider.java    From embedded-database-spring-test with Apache License 2.0 5 votes vote down vote up
private DatabaseInstance(DatabaseConfig config) throws IOException {
    EmbeddedPostgres.Builder builder = EmbeddedPostgres.builder();
    config.applyTo(builder);

    postgres = builder.start();

    DataSource dataSource = postgres.getDatabase("postgres", "postgres");
    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    Integer maxConnections = jdbcTemplate.queryForObject("show max_connections", Integer.class);

    semaphore = new Semaphore(maxConnections);
}
 
Example #27
Source File: LocalHistoryStoreImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public StoreEntry getStoreEntry(VCSFileProxy file, long ts) {
    Semaphore s = lock(file, "getStoreEntry"); // NOI18N
    try {
        return getStoreEntryIntern(file, ts);
    } finally {
        if(s != null) s.release();
    }
}
 
Example #28
Source File: NettyRemotingAbstractTest.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
@Test
public void testProcessResponseCommand_NullCallBack() throws InterruptedException {
    final Semaphore semaphore = new Semaphore(0);
    ResponseFuture responseFuture = new ResponseFuture(1, 3000, null,
        new SemaphoreReleaseOnlyOnce(semaphore));

    remotingAbstract.responseTable.putIfAbsent(1, responseFuture);

    RemotingCommand response = RemotingCommand.createResponseCommand(0, "Foo");
    response.setOpaque(1);
    remotingAbstract.processResponseCommand(null, response);

    assertThat(semaphore.availablePermits()).isEqualTo(1);
}
 
Example #29
Source File: MqttEmbeddedBrokerServiceTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void connectToEmbeddedServer() throws InterruptedException, IOException {
    ServiceConfiguration config = new ServiceConfiguration();
    config.username = "username";
    config.password = "password";
    config.port = 12345;
    config.secure = false;
    config.persistenceFile = "";

    subject.initialize(config);

    Semaphore semaphore = new Semaphore(1);
    semaphore.acquire();

    MqttBrokerConnection c = subject.getConnection();

    MqttConnectionObserver mqttConnectionObserver = (state, error) -> {
        if (state == MqttConnectionState.CONNECTED) {
            semaphore.release();
        }
    };
    c.addConnectionObserver(mqttConnectionObserver);
    if (c.connectionState() == MqttConnectionState.CONNECTED) {
        semaphore.release();
    }

    // Start the connection and wait until timeout or connected callback returns.
    semaphore.tryAcquire(3000, TimeUnit.MILLISECONDS);

    c.removeConnectionObserver(mqttConnectionObserver);

    assertThat(c.getUser(), is("username"));
    assertThat(c.getPassword(), is("password"));

    assertThat(c.connectionState(), is(MqttConnectionState.CONNECTED));
    verify(service).addBrokerConnection(anyString(), eq(c));
}
 
Example #30
Source File: FairQueuingPacketScheduler.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
private DroppingProducer(
   Semaphore available,
   BlockingQueue<T> queue, 
   RateLimiter rateLimit,
   PacketScheduler.PacketDropHandler<? super T> dropHandler,
   PacketScheduler.QueueStateHandler<? super T> queueHandler,
   int lowWaterMark,
   int highWaterMark
   ) {
   super(available, queue, rateLimit, dropHandler, queueHandler, lowWaterMark, highWaterMark);
}