Java 类java.util.concurrent.Semaphore 实例源码

项目:NetCom2    文件:TCPDefaultConnection.java   
@Override
protected synchronized void beforeSend(final Object object) {
    NetCom2Utils.assertNotNull(object);
    if (object.getClass().equals(Acknowledge.class)) {
        logging.trace("[TCP] No need to setup an synchronization mechanism an Acknowledge!");
        return;
    }
    logging.trace("[TCP] Locking access to send ..");
    communicationLock.lock();
    logging.debug("[TCP] Preparing send of " + object + " at Thread " + Thread.currentThread());
    final Semaphore semaphore = new Semaphore(1);
    logging.trace("[TCP] ClientMapping synchronization mechanism ..");
    synchronized (mapping) {
        mapping.put(object.getClass(), semaphore);
    }
    logging.trace("[TCP] Setting up Callback ..");
    receivingService.addReceivingCallback(new TCPAckCallback(object.getClass()));
}
项目:firebase-admin-java    文件:QueryTestIT.java   
@Test
public void testRemoveListener()
    throws TestFailure, ExecutionException, TimeoutException, InterruptedException {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp);

  final Semaphore semaphore = new Semaphore(0);
  ValueEventListener listener = ref.limitToLast(5)
      .addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {
          semaphore.release();
        }

        @Override
        public void onCancelled(DatabaseError error) {
        }
      });

  ref.setValueAsync(MapBuilder.of("a", 5, "b", 6));
  TestHelpers.waitFor(semaphore, 1);
  ref.limitToLast(5).removeEventListener(listener);
  new WriteFuture(ref, MapBuilder.of("a", 6, "b", 5)).timedGet();
  TestHelpers.waitForQueue(ref);

  assertEquals(0, semaphore.availablePermits());
}
项目:firebase-admin-java    文件:DataTestIT.java   
@Test
public void testSetPriority() throws InterruptedException {
  final DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp);

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

  assertTrue(semaphore.tryAcquire(1, TestUtils.TEST_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS));
}
项目:firebase-admin-java    文件:DataTestIT.java   
@Test
public void testUpdateAfterSetLeafNodeWorks() throws InterruptedException {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp);
  final Semaphore semaphore = new Semaphore(0);
  final Map<String, Object> expected = new MapBuilder().put("a", 1L).put("b", 2L).build();

  ref.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot snapshot) {
      if (DeepEquals.deepEquals(snapshot.getValue(), expected)) {
        semaphore.release();
      }
    }

    @Override
    public void onCancelled(DatabaseError error) {
    }
  });
  ref.setValueAsync(42);
  ref.updateChildrenAsync(expected);

  TestHelpers.waitFor(semaphore);
}
项目:doctemplate    文件:ConvertOdtToPdfTest_OO.java   
/**
 * @throws Exception
 */
@Test
public void test2() throws Exception {
    Semaphore semaphore = new Semaphore(10, true);
    for (int i = 0; i < MAX_THREAD_COUNT; i++) {
        new MultithreadingTest(i, semaphore, this).start();
        if (i > 0 && i % 100 == 0) {
            synchronized (this) {
                while (counter != i) {
                    wait();
                }
            }
        }
    }
    synchronized (this) {
        while (counter != MAX_THREAD_COUNT) {
            wait();
        }
        System.out.println("counter: " + counter);
    }
}
项目:firebase-admin-java    文件:TestHelpers.java   
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);
  }
项目:NetCom2    文件:RemoteAccessBlockRegistration.java   
@APILevel
void release(RemoteAccessCommunicationResponse response) {
    synchronized (responseMap) {
        responseMap.put(response.getUuid(), response);
    }
    Semaphore semaphore = getSemaphore(response.getUuid());

    if(semaphore == null) {
        return;
    }

    semaphore.release();
}
项目:AAVT    文件:Mp4Provider.java   
@Override
public Point open(SurfaceTexture surface) {
    try {
        if(!extractMedia()){
            return new Point(0,0);
        }
        mFrameSem=new Semaphore(0);
        mDecodeSem=new Semaphore(1);
        videoProvideEndFlag=false;
        isUserWantToStop=false;
        mAudioEncodeTrack=mStore.addTrack(mExtractor.getTrackFormat(mAudioDecodeTrack));
        MediaFormat format=mExtractor.getTrackFormat(mVideoDecodeTrack);
        mVideoDecoder = MediaCodec.createDecoderByType(format.getString(MediaFormat.KEY_MIME));
        mVideoDecoder.configure(format,new Surface(surface),null,0);
        mVideoDecoder.start();
        startDecodeThread();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return mVideoSize;
}
项目:openjdk-jdk10    文件:CheckedLockLoops.java   
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;
}
项目:firebase-admin-java    文件:RepoTest.java   
@Test
public void testRangeMergeUpdate() throws InterruptedException {
  final Repo repo = newRepo();
  final List<DataSnapshot> events = new ArrayList<>();
  QuerySpec spec = new QuerySpec(new Path("/rangeMerge"), QueryParams.DEFAULT_PARAMS);
  addCallback(repo, new ValueEventRegistration(repo, newValueEventListener(events), spec));

  final Semaphore semaphore = new Semaphore(0);
  final RangeMerge merge = new RangeMerge(ImmutableList.of("p1"),
      ImmutableList.of("p5"), ImmutableMap.of("p2", "v2", "p3", "v3"));
  repo.scheduleNow(new Runnable() {
    @Override
    public void run() {
      repo.onRangeMergeUpdate(
          ImmutableList.of("rangeMerge"), ImmutableList.of(merge), null);
      semaphore.release();
    }
  });
  waitFor(semaphore);
  assertEquals(1, events.size());
  assertNotNull(events.get(0));
  assertEquals(ImmutableMap.of("p2", "v2", "p3", "v3"), events.get(0).getValue());
}
项目:firebase-admin-java    文件:RepoTest.java   
@Test
public void testSetValue() throws InterruptedException {
  final Repo repo = newRepo();
  final List<DataSnapshot> events = new ArrayList<>();
  final Path path = new Path("/foo");
  QuerySpec spec = new QuerySpec(path, QueryParams.DEFAULT_PARAMS);
  addCallback(repo, new ValueEventRegistration(repo, newValueEventListener(events), spec));

  final Semaphore semaphore = new Semaphore(0);
  repo.scheduleNow(new Runnable() {
    @Override
    public void run() {
      repo.setValue(path, NodeUtilities.NodeFromJSON("setValue"), null);
      semaphore.release();
    }
  });
  waitFor(semaphore);
  assertEquals(1, events.size());
  assertNotNull(events.get(0));
  assertEquals("setValue", events.get(0).getValue(String.class));
}
项目:boohee_v5.6    文件:MQPhotoPreviewActivity.java   
private void processLogic(Bundle savedInstanceState) {
    this.mSaveImgDir = (File) getIntent().getSerializableExtra(EXTRA_SAVE_IMG_DIR);
    if (this.mSaveImgDir == null) {
        this.mDownloadIv.setVisibility(4);
    }
    this.mPreviewImages = getIntent().getStringArrayListExtra(EXTRA_PREVIEW_IMAGES);
    this.mIsSinglePreview = getIntent().getBooleanExtra(EXTRA_IS_SINGLE_PREVIEW, false);
    if (this.mIsSinglePreview) {
        this.mPreviewImages = new ArrayList();
        this.mPreviewImages.add(getIntent().getStringExtra(EXTRA_PHOTO_PATH));
    }
    int currentPosition = getIntent().getIntExtra(EXTRA_CURRENT_POSITION, 0);
    this.mContentHvp.setAdapter(new ImagePageAdapter());
    this.mContentHvp.setCurrentItem(currentPosition);
    renderTitleTv();
    this.mSemaphore = new Semaphore(1);
    this.mTitleRl.postDelayed(new Runnable() {
        public void run() {
            MQPhotoPreviewActivity.this.hiddenTitlebar();
        }
    }, 2000);
}
项目:drd    文件:MiniConnectionPoolManager.java   
/**
 * Constructs a MiniConnectionPoolManager object.
 *
 * @param dataSource the data source for the connections.
 * @param maxConnections the maximum number of connections.
 * @param timeout the maximum time in seconds to wait for a free connection.
 */
public MiniConnectionPoolManager(ConnectionPoolDataSource dataSource, int maxConnections,
    int timeout) {
    this.dataSource = dataSource;
    this.maxConnections = maxConnections;
    this.timeoutMs = timeout * 1000L;
    try {
        logWriter = dataSource.getLogWriter();
    } catch (SQLException e) {
    }
    if (maxConnections < 1) {
        throw new IllegalArgumentException("Invalid maxConnections value.");
    }
    semaphore = new Semaphore(maxConnections, true);
    recycledConnections = new LinkedList<PooledConnection>();
    poolConnectionEventListener = new PoolConnectionEventListener();
}
项目:GitHub    文件:SharedByteArray.java   
public SharedByteArray(
    MemoryTrimmableRegistry memoryTrimmableRegistry,
    PoolParams params) {
  Preconditions.checkNotNull(memoryTrimmableRegistry);
  Preconditions.checkArgument(params.minBucketSize > 0);
  Preconditions.checkArgument(params.maxBucketSize >= params.minBucketSize);

  mMaxByteArraySize = params.maxBucketSize;
  mMinByteArraySize = params.minBucketSize;
  mByteArraySoftRef = new OOMSoftReference<byte[]>();
  mSemaphore = new Semaphore(1);
  mResourceReleaser = new ResourceReleaser<byte[]>() {
    @Override
    public void release(byte[] unused) {
      mSemaphore.release();
    }
  };

  memoryTrimmableRegistry.registerMemoryTrimmable(this);
}
项目:incubator-netbeans    文件:SearchScopeListTest.java   
public void testSearchScopesNotifiedAboutChangesInEDT()
        throws InterruptedException {
    CustomSearchScope css = new CustomSearchScope(true, 1);
    SearchScopeList ssl = new SearchScopeList(css);
    final Semaphore s = new Semaphore(0);
    final AtomicBoolean notifiedInEDT = new AtomicBoolean(false);
    ssl.addChangeListener(new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent e) {
            notifiedInEDT.set(EventQueue.isDispatchThread());
            s.release();
        }
    });
    css.fireChangeEvent();
    boolean acqrd = s.tryAcquire(10, TimeUnit.SECONDS);
    assertTrue("Should be notified in EDT", acqrd && notifiedInEDT.get());
}
项目:MyRepository    文件:ImageLoader.java   
/**
     * 初始化
     *
     * @param threadCount
     * @param type
     */
    private void init(int threadCount, Type type) {
        initBackThread();

        // 获取我们应用的最大可用内存
        int maxMemory = (int) Runtime.getRuntime().maxMemory();
        int cacheMemory = maxMemory / 8;
        mLruCache = new LruCache<String, Bitmap>(cacheMemory) {
            @Override
            protected int sizeOf(String key, Bitmap value) {
//                return value.getRowBytes() * value.getHeight();
                return value.getByteCount();
            }

        };

        // 创建线程池
        mThreadPool = Executors.newFixedThreadPool(threadCount);
        mTaskQueue = new LinkedList<Runnable>();
        mType = type;
        mSemaphoreThreadPool = new Semaphore(threadCount);
    }
项目:firebase-admin-java    文件:OrderByTestIT.java   
@Test
public void testChildAddedEvents() throws InterruptedException {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp) ;

  Map<String, Object> initial =
      new MapBuilder()
          .put("a", MapBuilder.of("value", 5L))
          .put("c", MapBuilder.of("value", 3L))
          .build();

  final List<String> snapshotNames = new ArrayList<>();
  final List<String> prevNames = new ArrayList<>();
  final Semaphore semaphore = new Semaphore(0);
  final ChildEventListener testListener =
      ref.orderByChild("value")
          .addChildEventListener(
              new TestChildEventListener() {
                @Override
                public void onChildAdded(DataSnapshot snap, String prevName) {
                  snapshotNames.add(snap.getKey());
                  prevNames.add(prevName);
                  semaphore.release();
                }
              });

  ref.setValueAsync(initial);
  TestHelpers.waitFor(semaphore, 2);
  Assert.assertEquals(Arrays.asList("c", "a"), snapshotNames);
  Assert.assertEquals(Arrays.asList(null, "c"), prevNames);

  Map<String, Object> updates = new HashMap<>();
  updates.put("b", MapBuilder.of("value", 4));
  updates.put("d", MapBuilder.of("value", 2));
  ref.updateChildrenAsync(updates);

  TestHelpers.waitFor(semaphore, 2);
  Assert.assertEquals(Arrays.asList("c", "a", "d", "b"), snapshotNames);
  Assert.assertEquals(Arrays.asList(null, "c", null, "c"), prevNames);
  ref.removeEventListener(testListener);
}
项目:firebase-admin-java    文件:OrderByTestIT.java   
@Test
public void testServerRespectsKeyIndex()
    throws InterruptedException, ExecutionException, TimeoutException, TestFailure {
  List<DatabaseReference> refs = IntegrationTestUtils.getRandomNode(masterApp, 2);
  DatabaseReference writer = refs.get(0);
  DatabaseReference reader = refs.get(1);

  Map<String, Object> initial = MapBuilder.of("a", 1, "b", 2, "c", 3);
  // If the server doesn't respect the index, it will send down limited data, but with no
  // offset, so the expected and actual data don't match.
  Query query = reader.orderByKey().startAt("b").limitToFirst(2);

  new WriteFuture(writer, initial).timedGet();

  final List<String> actualChildren = new ArrayList<>();
  final Semaphore semaphore = new Semaphore(0);
  ValueEventListener valueListener =
      query.addValueEventListener(
          new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot snapshot) {
              for (DataSnapshot child : snapshot.getChildren()) {
                actualChildren.add(child.getKey());
              }
              semaphore.release();
            }

            @Override
            public void onCancelled(DatabaseError error) {
              Assert.fail();
            }
          });

  TestHelpers.waitFor(semaphore);
  Assert.assertEquals(ImmutableList.of("b", "c"), actualChildren);

  // cleanup
  reader.removeEventListener(valueListener);
}
项目:firebase-admin-java    文件:QueryTestIT.java   
@Test
public void testNodeWithDefaultListener()
    throws TestFailure, ExecutionException, TimeoutException, InterruptedException {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp);

  new WriteFuture(ref, new MapBuilder().put("a", 1).put("b", 2).put("c", 3).put("d", 4)
      .put("e", 5).put("f", 6).build()).timedGet();

  final AtomicInteger onCalled = new AtomicInteger(0);
  final Semaphore semaphore = new Semaphore(0);
  ref.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot snapshot) {
      // Should only be called once
      if (onCalled.incrementAndGet() == 1) {
        semaphore.release(1);
      }
    }

    @Override
    public void onCancelled(DatabaseError error) {
    }
  });

  TestHelpers.waitFor(semaphore);
  assertEquals(1, onCalled.get());

  DataSnapshot snap = TestHelpers.getSnap(ref.limitToLast(1));
  TestHelpers.assertDeepEquals(MapBuilder.of("f", 6L), snap.getValue());
}
项目:openjdk-jdk10    文件:SemaphoreTest.java   
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());
    }
}
项目:datarouter    文件:SemaphoreTool.java   
public static void acquire(Semaphore semaphore){
    try{
        semaphore.acquire();
    }catch(InterruptedException e){
        throw new RuntimeException(e);
    }
}
项目:firebase-admin-java    文件:QueryTestIT.java   
@Test
public void testRemoveListenerOnDefaultQuery()
    throws InterruptedException, ExecutionException, TimeoutException, TestFailure {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp);
  new WriteFuture(ref.child("a"), "foo", 100).timedGet();

  final Semaphore semaphore = new Semaphore(0);
  final DataSnapshot[] snapshotHolder = new DataSnapshot[1];

  ValueEventListener listener = ref.startAt(99).addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot snapshot) {
      snapshotHolder[0] = snapshot;
      semaphore.release();
    }

    @Override
    public void onCancelled(DatabaseError error) {
      fail("Unexpected error: " + error);
    }
  });

  TestHelpers.waitFor(semaphore);
  Map<String, Object> expected = MapBuilder.of("a", "foo");
  TestHelpers.assertDeepEquals(expected, snapshotHolder[0].getValue());

  ref.removeEventListener(listener);

  new WriteFuture(ref.child("a"), "bar", 100).timedGet();
  // the listener is removed the value should have not changed
  TestHelpers.assertDeepEquals(expected, snapshotHolder[0].getValue());
}
项目:jobson    文件:JobExecutorTest.java   
@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);
}
项目:doctemplate    文件:ODTMergeEngineTest.java   
/**
 * Test 4: Multithreading-Test.
 *
 * @throws Exception
 */
@Test
public void test2() throws Exception {

    String expected = new String(getBytes("result1.xml"));

    Semaphore semaphore = new Semaphore(100, true);
    for (int i = 0; i < 100; i++) {
        semaphore.acquire();
        new MultithreadingTest(i, semaphore, expected).start();
    }
    semaphore.acquire(100);
}
项目:firebase-admin-java    文件:DataTestIT.java   
@Test
public void testUpdateChangesAreStoredCorrectlyInServer()
    throws TestFailure, ExecutionException, TimeoutException, InterruptedException {
  List<DatabaseReference> refs = IntegrationTestUtils.getRandomNode(masterApp, 2);
  final DatabaseReference writer = refs.get(0);
  final DatabaseReference reader = refs.get(1);

  new WriteFuture(writer,
      new MapBuilder().put("a", 1).put("b", 2).put("c", 3).put("d", 4).build()).timedGet();

  final Semaphore semaphore = new Semaphore(0);
  writer.updateChildren(MapBuilder.of("a", 42),
      new DatabaseReference.CompletionListener() {
        @Override
        public void onComplete(DatabaseError error, DatabaseReference ref) {
          assertNull(error);
          semaphore.release(1);
        }
      });

  TestHelpers.waitFor(semaphore);

  DataSnapshot snap = TestHelpers.getSnap(reader);
  Map<String, Object> expected = new MapBuilder().put("a", 42L).put("b", 2L).put("c", 3L)
      .put("d", 4L).build();
  Object result = snap.getValue();
  TestHelpers.assertDeepEquals(expected, result);
}
项目:firebase-admin-java    文件:DataTestIT.java   
@Test
public void testUpdateAffectPriorityRemotely()
    throws TestFailure, ExecutionException, TimeoutException, InterruptedException {
  List<DatabaseReference> refs = IntegrationTestUtils.getRandomNode(masterApp, 2);
  DatabaseReference reader = refs.get(0);
  DatabaseReference writer = refs.get(1);

  new WriteFuture(writer, new MapBuilder().put("a", 1).put("b", 2).put("c", 3).build(), "testpri")
      .timedGet();

  DataSnapshot snap = TestHelpers.getSnap(reader);
  assertEquals("testpri", snap.getPriority());

  final Semaphore semaphore = new Semaphore(0);
  writer.updateChildren(MapBuilder.of("a", 4),
      new DatabaseReference.CompletionListener() {
        @Override
        public void onComplete(DatabaseError error, DatabaseReference ref) {
          assertNull(error);
          semaphore.release(1);
        }
      });

  TestHelpers.waitFor(semaphore);
  snap = TestHelpers.getSnap(reader);
  assertEquals("testpri", snap.getPriority());
}
项目:Java-9-Concurrency-Cookbook-Second-Edition    文件:PrintQueue.java   
/**
 * Constructor of the class. It initializes the three objects
 */
public PrintQueue(){
    semaphore=new Semaphore(3);
    freePrinters=new boolean[3];
    for (int i=0; i<3; i++){
        freePrinters[i]=true;
    }
    lockPrinters=new ReentrantLock();
}
项目:firebase-admin-java    文件:DataTestIT.java   
@Test
public void testDeepUpdate() throws InterruptedException, TestFailure, TimeoutException {
  List<DatabaseReference> refs = IntegrationTestUtils.getRandomNode(masterApp, 2);
  final DatabaseReference writer = refs.get(0);
  final DatabaseReference reader = refs.get(1);

  final ReadFuture readFuture = ReadFuture.untilCount(writer, 2);

  writer.setValueAsync(
      new MapBuilder().put("a", new MapBuilder().put("aa", 1).put("ab", 2).build()).build());
  Map<String, Object> expected = new MapBuilder()
      .put("a", new MapBuilder().put("aa", 10L).put("ab", 20L).build()).build();
  Map<String, Object> update = new MapBuilder().put("a/aa", 10).put(".priority", 3.0)
      .put("a/ab", new MapBuilder().put(".priority", 2.0).put(".value", 20).build()).build();

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

  TestHelpers.waitFor(semaphore);

  DataSnapshot snap = TestHelpers.getSnap(reader);
  TestHelpers.assertDeepEquals(expected, snap.getValue());
  assertEquals(3.0, snap.getPriority());

  snap = readFuture.timedGet().get(1).getSnapshot();
  TestHelpers.assertDeepEquals(expected, snap.getValue());
  assertEquals(3.0, snap.getPriority());

  snap = TestHelpers.getSnap(reader.child("a/ab"));
  assertEquals(2.0, snap.getPriority());
}
项目:firebase-admin-java    文件:DataTestIT.java   
@Test
public void testUpdateFiresCorrectEventWhenDeletingChild()
    throws TestFailure, ExecutionException, TimeoutException, InterruptedException {
  List<DatabaseReference> refs = IntegrationTestUtils.getRandomNode(masterApp, 2);
  DatabaseReference writer = refs.get(0);
  DatabaseReference reader = refs.get(1);

  final ReadFuture writerFuture = ReadFuture.untilCountAfterNull(writer, 2);
  new WriteFuture(writer, new MapBuilder().put("a", 12).put("b", 6).build()).timedGet();
  final Semaphore semaphore = new Semaphore(0);
  final ReadFuture readerFuture = new ReadFuture(reader, new ReadFuture.CompletionCondition() {
    @Override
    public boolean isComplete(List<EventRecord> events) {
      if (events.size() == 1) {
        semaphore.release();
      }
      return events.size() == 2;
    }
  });

  TestHelpers.waitFor(semaphore);

  writer.updateChildrenAsync(MapBuilder.of("a", null));
  DataSnapshot snap = writerFuture.timedGet().get(1).getSnapshot();

  Map<String, Object> expected = MapBuilder.of("b", 6L);
  TestHelpers.assertDeepEquals(expected, snap.getValue());

  snap = readerFuture.timedGet().get(1).getSnapshot();

  TestHelpers.assertDeepEquals(expected, snap.getValue());
}
项目:https-github.com-apache-zookeeper    文件:FLERestartTest.java   
@Before
public void setUp() throws Exception {
    count = 3;
    peers = new HashMap<Long,QuorumServer>(count);
    restartThreads = new ArrayList<FLERestartThread>(count);
    tmpdir = new File[count];
    port = new int[count];
    finish = new Semaphore(0);
}
项目:firebase-admin-java    文件:DataTestIT.java   
@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());
}
项目:mug    文件:ParallelizerTest.java   
private static Stream<Runnable> serialTasks(Runnable... tasks) {
  Semaphore semaphore = new Semaphore(1);
  return asList(tasks).stream().map(task -> {
    semaphore.acquireUninterruptibly();
    return () -> {
      semaphore.release();
      task.run();
    };
  });
}
项目:knime-activelearning    文件:KernelCalculator.java   
public CalculateKernelValuesRunnable(final int trainingStart,
        final int trainingEnd, final int testStart, final int testEnd,
        final double[][] training, final double[][] test,
        final double[][] result, final KernelFunction kernelFunction,
        final Semaphore semaphore) {
    m_trainingStart = trainingStart;
    m_trainingEnd = trainingEnd;
    m_testStart = testStart;
    m_testEnd = testEnd;
    m_training = training;
    m_test = test;
    m_result = result;
    m_kernelFunction = kernelFunction;
    m_semaphore = semaphore;
}
项目:firebase-admin-java    文件:RealtimeTestIT.java   
@Test
public void testWritesToSameLocationWhileOfflineAreInOrder()
    throws InterruptedException, ExecutionException, TimeoutException, TestFailure {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp);

  DatabaseReference.goOffline();
  for (int i = 0; i < 100; i++) {
    ref.setValueAsync(i);
  }
  // This should be the last write and the actual value
  WriteFuture future = new WriteFuture(ref, 100);
  DatabaseReference.goOnline();
  future.timedGet();

  final Semaphore semaphore = new Semaphore(0);
  ref.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot snapshot) {
      assertEquals(100L, snapshot.getValue());
      semaphore.release();
    }

    @Override
    public void onCancelled(DatabaseError error) {
      fail("Shouldn't be cancelled");
    }
  });

  TestHelpers.waitFor(semaphore);
}
项目:firebase-admin-java    文件:ReadFuture.java   
private ReadFuture(
    final Query ref, final CompletionCondition condition, final boolean ignoreFirstNull) {
  semaphore = new Semaphore(0);
  this.valueEventListener =
      new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {
          if (ignoreFirstNull && events.size() == 0 && snapshot.getValue() == null) {
            return;
          }
          events.add(new EventRecord(snapshot, Event.EventType.VALUE, null));
          try {
            if (condition.isComplete(events)) {
              ref.removeEventListener(valueEventListener);
              finish();
            }
          } catch (Exception e) {
            exception = e;
            finish();
          }
        }

        @Override
        public void onCancelled(DatabaseError error) {
          wasCancelled = true;
          finish();
        }
      };
  ref.addValueEventListener(this.valueEventListener);
}
项目:jobson    文件:JobManagerTest.java   
@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");
    }
}
项目:openjdk-jdk10    文件:SemaphoreTest.java   
public void testReleaseAcquireDifferentThreads(boolean fair,
                                               final AcquireMethod acquirer) {
    final Semaphore s = new Semaphore(0, fair);
    final int rounds = 4;
    long startTime = System.nanoTime();
    Thread t = newStartedThread(new CheckedRunnable() {
        public void realRun() throws InterruptedException {
            for (int i = 0; i < rounds; i++) {
                assertFalse(s.hasQueuedThreads());
                if (i % 2 == 0)
                    acquirer.acquire(s);
                else
                    acquirer.acquire(s, 3);
            }}});

    for (int i = 0; i < rounds; i++) {
        while (! (s.availablePermits() == 0 && s.hasQueuedThreads()))
            Thread.yield();
        assertTrue(t.isAlive());
        if (i % 2 == 0)
            s.release();
        else
            s.release(3);
    }
    awaitTermination(t);
    assertEquals(0, s.availablePermits());
    assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
}
项目:firebase-admin-java    文件:DefaultRunLoopTest.java   
@Test
public void testExceptionHandling() throws InterruptedException {
  MockRunLoop runLoop = new MockRunLoop();
  final Semaphore semaphore = new Semaphore(0);
  UncaughtExceptionHandler exceptionHandler = new UncaughtExceptionHandler() {
    @Override
    public void uncaughtException(Thread t, Throwable e) {
      semaphore.release();
    }
  };
  runLoop.setExceptionHandler(exceptionHandler);
  assertSame(exceptionHandler, runLoop.getExceptionHandler());

  try {
    assertEquals(0, runLoop.getThreadPool().getCorePoolSize());
    runLoop.scheduleNow(new Runnable() {
      @Override
      public void run() {
        throw new RuntimeException("test error");
      }
    });
    assertEquals(1, runLoop.getThreadPool().getCorePoolSize());
    semaphore.acquire();

    synchronized (runLoop.errors) {
      if (runLoop.errors.isEmpty()) {
        runLoop.errors.wait(TestUtils.TEST_TIMEOUT_MILLIS);
      }
    }
    assertEquals(1, runLoop.errors.size());
  } finally {
    runLoop.getExecutorService().shutdownNow();
  }
}
项目:googles-monorepo-demo    文件:Striped.java   
/**
 * Creates a {@code Striped<Semaphore>} with eagerly initialized, strongly referenced semaphores,
 * with the specified number of permits.
 *
 * @param stripes the minimum number of stripes (semaphores) required
 * @param permits the number of permits in each semaphore
 * @return a new {@code Striped<Semaphore>}
 */
public static Striped<Semaphore> semaphore(int stripes, final int permits) {
  return new CompactStriped<Semaphore>(
      stripes,
      new Supplier<Semaphore>() {
        @Override
        public Semaphore get() {
          return new PaddedSemaphore(permits);
        }
      });
}
项目:firebase-admin-java    文件:RepoTest.java   
@Test
public void testDataUpdateForQuery() throws InterruptedException {
  final Repo repo = newRepo();
  final List<DataSnapshot> events = new ArrayList<>();
  QuerySpec spec = new QuerySpec(new Path("/bar"),
      QueryParams.DEFAULT_PARAMS.orderBy(ValueIndex.getInstance()).limitToFirst(10));
  addCallback(repo, new ValueEventRegistration(repo, newValueEventListener(events), spec));

  final Semaphore semaphore = new Semaphore(0);
  final Map<String, String> update = ImmutableMap.of("key1", "value1");

  repo.scheduleNow(new Runnable() {
    @Override
    public void run() {
      repo.onDataUpdate(ImmutableList.of("bar"), update, false, 1L);
      semaphore.release();
    }
  });
  waitFor(semaphore);
  assertEquals(1, events.size());
  assertNotNull(events.get(0));
  assertEquals(update, events.get(0).getValue());

  repo.scheduleNow(new Runnable() {
    @Override
    public void run() {
      repo.onDataUpdate(ImmutableList.of("bar"), ImmutableMap.of("key2", "value2"), true, 1L);
      semaphore.release();
    }
  });
  waitFor(semaphore);
  assertEquals(2, events.size());
  assertNotNull(events.get(1));
  assertEquals(ImmutableMap.of("key1", "value1", "key2", "value2"), events.get(1).getValue());
}