Java Code Examples for java.util.concurrent.SynchronousQueue#put()

The following examples show how to use java.util.concurrent.SynchronousQueue#put() . 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: ReferenceCleanerTests.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
public void testReferenceCleaner() throws Exception {
    assertStaticHelperClass(ReferenceCleaner.class);
    final SynchronousQueue<String> queue = new SynchronousQueue<String>();
    Object obj = new Object();
    ReferenceCleaner.Soft<Object> soft = new ReferenceCleaner.Soft<Object>(obj) {
        public void remove() throws Exception {
            queue.put("soft");
            Thread.currentThread().interrupt();
        }
    };
    ReferenceCleaner.Weak<Object> weak = new ReferenceCleaner.Weak<Object>(obj) {
        public void remove() throws Exception {
            queue.put("weak");
            throw new RuntimeException();
        }
    };
    new ReferenceCleaner.Phantom<Object>(obj) {
        public void remove() throws Exception {
            queue.put("phantom");
        }
    };
    HashSet<String> foundEvents = new HashSet<String>();
    useAllMemory();
    assertSame("still-soft", obj, soft.get());
    assertSame("still-weak", obj, weak.get());
    assertNull("no event", queue.poll(100, TimeUnit.MILLISECONDS));
    useAllMemory();
    foundEvents.add(queue.poll(100, TimeUnit.MILLISECONDS));
    foundEvents.add(queue.poll(100, TimeUnit.MILLISECONDS));
    foundEvents.add(queue.poll(100, TimeUnit.MILLISECONDS));
    useAllMemory();
    foundEvents.add(queue.poll(100, TimeUnit.MILLISECONDS));
    foundEvents.remove(null);
    assertFalse("no null", foundEvents.contains(null));
    assertNull("no-soft", soft.get());
    assertNull("no-weak", weak.get());
    assertTrue("soft event", foundEvents.contains("soft"));
    assertTrue("weak event", foundEvents.contains("weak"));
    assertTrue("phantom event", foundEvents.contains("phantom"));
}
 
Example 2
Source File: SingletonValueJUnitTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public void testMultithread() throws Exception {
  int count = 100;
  
  ExecutorService exec = Executors.newFixedThreadPool(count);
  final SynchronousQueue<Object> sync = new SynchronousQueue<Object>(true);
  final CountDownLatch waiting = new CountDownLatch(count - 1);
  
  final MockCallable call = new MockCallable(sync, waiting, false);
  final SingletonValue<MockCallable> cc = new SingletonValue<MockCallable>(call);

  final CyclicBarrier barrier = new CyclicBarrier(count + 1);
  Collection<Future<MockCallable>> results = new ArrayList<Future<MockCallable>>();
  invoke(count, exec, cc, barrier, results);

  // wait for everyone
  barrier.await();
  waiting.await();
  
  // now release the originator
  sync.put(new Object());
  
  for (Future<MockCallable> fu : results) {
    assertEquals(call, fu.get());
  }
  
  exec.shutdownNow();
}
 
Example 3
Source File: SingletonValueJUnitTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public void testMultithreadError() throws Exception {
  int count = 100;
  
  ExecutorService exec = Executors.newFixedThreadPool(count);
  final SynchronousQueue<Object> sync = new SynchronousQueue<Object>(true);
  final CountDownLatch waiting = new CountDownLatch(count - 1);

  final MockCallable call = new MockCallable(sync, waiting, true);
  final SingletonValue<MockCallable> cc = new SingletonValue<MockCallable>(call);

  final CyclicBarrier barrier = new CyclicBarrier(count + 1);
  Collection<Future<MockCallable>> results = new ArrayList<Future<MockCallable>>();
  invoke(count, exec, cc, barrier, results);
  
  // wait for everyone
  barrier.await();
  waiting.await();

  // now release the originator
  sync.put(new Object());
  
  for (Future<MockCallable> fu : results) {
    try {
      fu.get();
      fail("Expected IOException");
    } catch (Exception e) {
    }
  }
  
  exec.shutdownNow();
}
 
Example 4
Source File: SingletonValueJUnitTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public void testMultithread() throws Exception {
  int count = 100;
  
  ExecutorService exec = Executors.newFixedThreadPool(count);
  final SynchronousQueue<Object> sync = new SynchronousQueue<Object>(true);
  final CountDownLatch waiting = new CountDownLatch(count - 1);
  
  final MockCallable call = new MockCallable(sync, waiting, false);
  final SingletonValue<MockCallable> cc = new SingletonValue<MockCallable>(call);

  final CyclicBarrier barrier = new CyclicBarrier(count + 1);
  Collection<Future<MockCallable>> results = new ArrayList<Future<MockCallable>>();
  invoke(count, exec, cc, barrier, results);

  // wait for everyone
  barrier.await();
  waiting.await();
  
  // now release the originator
  sync.put(new Object());
  
  for (Future<MockCallable> fu : results) {
    assertEquals(call, fu.get());
  }
  
  exec.shutdownNow();
}
 
Example 5
Source File: SingletonValueJUnitTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public void testMultithreadError() throws Exception {
  int count = 100;
  
  ExecutorService exec = Executors.newFixedThreadPool(count);
  final SynchronousQueue<Object> sync = new SynchronousQueue<Object>(true);
  final CountDownLatch waiting = new CountDownLatch(count - 1);

  final MockCallable call = new MockCallable(sync, waiting, true);
  final SingletonValue<MockCallable> cc = new SingletonValue<MockCallable>(call);

  final CyclicBarrier barrier = new CyclicBarrier(count + 1);
  Collection<Future<MockCallable>> results = new ArrayList<Future<MockCallable>>();
  invoke(count, exec, cc, barrier, results);
  
  // wait for everyone
  barrier.await();
  waiting.await();

  // now release the originator
  sync.put(new Object());
  
  for (Future<MockCallable> fu : results) {
    try {
      fu.get();
      fail("Expected IOException");
    } catch (Exception e) {
    }
  }
  
  exec.shutdownNow();
}
 
Example 6
Source File: InBandBytestreamTest.java    From Smack with Apache License 2.0 4 votes vote down vote up
/**
 * An In-Band Bytestream should be successfully established using IQ stanzas.
 *
 * @throws Exception should not happen
 */
public void testInBandBytestreamWithIQStanzas() throws Exception {

    XMPPConnection initiatorConnection = getConnection(0);
    XMPPConnection targetConnection = getConnection(1);

    // test data
    Random rand = new Random();
    final byte[] data = new byte[dataSize];
    rand.nextBytes(data);
    final SynchronousQueue<byte[]> queue = new SynchronousQueue<byte[]>();

    InBandBytestreamManager targetByteStreamManager = InBandBytestreamManager.getByteStreamManager(targetConnection);

    InBandBytestreamListener incomingByteStreamListener = new InBandBytestreamListener() {

        public void incomingBytestreamRequest(InBandBytestreamRequest request) {
            InputStream inputStream;
            try {
                inputStream = request.accept().getInputStream();
                byte[] receivedData = new byte[dataSize];
                int totalRead = 0;
                while (totalRead < dataSize) {
                    int read = inputStream.read(receivedData, totalRead, dataSize - totalRead);
                    totalRead += read;
                }
                queue.put(receivedData);
            }
            catch (Exception e) {
                fail(e.getMessage());
            }
        }

    };
    targetByteStreamManager.addIncomingBytestreamListener(incomingByteStreamListener);

    InBandBytestreamManager initiatorByteStreamManager = InBandBytestreamManager.getByteStreamManager(initiatorConnection);

    OutputStream outputStream = initiatorByteStreamManager.establishSession(
                    targetConnection.getUser()).getOutputStream();

    // verify stream
    outputStream.write(data);
    outputStream.flush();
    outputStream.close();

    assertEquals("received data not equal to sent data", data, queue.take());

}
 
Example 7
Source File: InBandBytestreamTest.java    From Smack with Apache License 2.0 4 votes vote down vote up
/**
 * An In-Band Bytestream should be successfully established using message stanzas.
 *
 * @throws Exception should not happen
 */
public void testInBandBytestreamWithMessageStanzas() throws Exception {

    XMPPConnection initiatorConnection = getConnection(0);
    XMPPConnection targetConnection = getConnection(1);

    // test data
    Random rand = new Random();
    final byte[] data = new byte[dataSize];
    rand.nextBytes(data);
    final SynchronousQueue<byte[]> queue = new SynchronousQueue<byte[]>();

    InBandBytestreamManager targetByteStreamManager = InBandBytestreamManager.getByteStreamManager(targetConnection);

    InBandBytestreamListener incomingByteStreamListener = new InBandBytestreamListener() {

        public void incomingBytestreamRequest(InBandBytestreamRequest request) {
            InputStream inputStream;
            try {
                inputStream = request.accept().getInputStream();
                byte[] receivedData = new byte[dataSize];
                int totalRead = 0;
                while (totalRead < dataSize) {
                    int read = inputStream.read(receivedData, totalRead, dataSize - totalRead);
                    totalRead += read;
                }
                queue.put(receivedData);
            }
            catch (Exception e) {
                fail(e.getMessage());
            }
        }

    };
    targetByteStreamManager.addIncomingBytestreamListener(incomingByteStreamListener);

    InBandBytestreamManager initiatorByteStreamManager = InBandBytestreamManager.getByteStreamManager(initiatorConnection);
    initiatorByteStreamManager.setStanza(StanzaType.MESSAGE);

    OutputStream outputStream = initiatorByteStreamManager.establishSession(
                    targetConnection.getUser()).getOutputStream();

    // verify stream
    outputStream.write(data);
    outputStream.flush();
    outputStream.close();

    assertEquals("received data not equal to sent data", data, queue.take());

}
 
Example 8
Source File: WorkerProcessPoolTest.java    From buck with Apache License 2.0 4 votes vote down vote up
@Test
public void canReturnAndBorrowWorkersWhileStartingUpOtherWorkers() throws Exception {
  SynchronousQueue<Future<WorkerProcess>> workers = new SynchronousQueue<>();
  WorkerProcessPool pool = createPool(2, workers);
  CountDownLatch firstThreadWaitingToBorrowProcess = new CountDownLatch(1);
  CountDownLatch secondThreadWaitingForWorker = new CountDownLatch(1);

  AtomicReference<WorkerProcess> firstBorrowedWorker = new AtomicReference<>();
  AtomicReference<WorkerProcess> secondBorrowedWorker = new AtomicReference<>();

  // thread 1, attempting to borrow a worker
  Thread firstThread =
      testThreads.startThread(
          () -> {
            try (BorrowedWorkerProcess worker = pool.borrowWorkerProcess()) {
              firstThreadWaitingToBorrowProcess.countDown();
              firstBorrowedWorker.set(worker.get());
            }
            try (BorrowedWorkerProcess worker = pool.borrowWorkerProcess()) {
              secondThreadWaitingForWorker.await();
              secondBorrowedWorker.set(worker.get());
            }
          });

  // transfer a fake worker to thread 1
  workers.put(CompletableFuture.completedFuture(new FakeWorkerProcess(ImmutableMap.of())));

  firstThreadWaitingToBorrowProcess.await();

  // thread 2, attempting to borrow a worker
  testThreads.startThread(borrowWorkerProcessWithoutReturning(pool, concurrentSet()));

  // transfer an incomplete future to thread 2. Thread 2 is blocked on @{link Future#get}.
  workers.put(new CompletableFuture<>());

  // thread 1 continues, returns the worker, and borrows another one
  secondThreadWaitingForWorker.countDown();

  firstThread.join(WAIT_FOR_TEST_THREADS_TIMEOUT);
  // here, thread 1 has borrowed a worker two times, or is blocked returning the first worker.

  assertThat(secondBorrowedWorker.get(), is(firstBorrowedWorker.get()));
}