java.util.concurrent.CyclicBarrier Java Examples

The following examples show how to use java.util.concurrent.CyclicBarrier. 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: OmegaContextTest.java    From servicecomb-pack with Apache License 2.0 7 votes vote down vote up
@Test
public void eachThreadGetsDifferentGlobalTxId() throws Exception {
  final CyclicBarrier barrier = new CyclicBarrier(2);

  Runnable runnable = exceptionalRunnable(new ExceptionalRunnable() {

    @Override
    public void run() throws Exception {
      String txId = UUID.randomUUID().toString();
      omegaContext.setGlobalTxId(txId);
      barrier.await();

      assertThat(omegaContext.globalTxId(), is(txId));
    }
  });

  Future f1 = executor.submit(runnable);                                      ;
  Future f2 = executor.submit(runnable);
  f1.get();
  f2.get();

}
 
Example #2
Source File: LightwaveRfBindingFunctionalTest.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
private DatagramPacket sendCommand(Item item, String itemConfig, Command command) throws Exception {
    // Set up sockets for testing
    DatagramPacket sentPacket = new DatagramPacket(new byte[1024], 1024);
    CyclicBarrier barrier = new CyclicBarrier(2);
    doAnswer(waitIndefinitely()).when(mockReceiveSocket).receive(any(DatagramPacket.class));
    doAnswer(waitIndefinitely()).when(mockReceiveSocket2).receive(any(DatagramPacket.class));
    doAnswer(transmitAnswer(sentPacket, barrier)).when(mockTransmitSocket).send(any(DatagramPacket.class));

    // Setup Item config
    bindingProvider.processBindingConfiguration(CONTEXT, item, itemConfig);
    binding.addBindingProvider(bindingProvider);

    // Activate the binding ready for the test
    binding.activateForTesting();

    // Send the command
    binding.internalReceiveCommand(item.getName(), command);

    // Wait till the socket has sent the command
    barrier.await(1000, TimeUnit.MILLISECONDS);
    return sentPacket;
}
 
Example #3
Source File: BidClientRunnable.java    From dubbox with Apache License 2.0 6 votes vote down vote up
public BidClientRunnable(String protocol, String serialization, String targetIP, int targetPort, int clientNums, int rpcTimeout,
                          CyclicBarrier barrier, CountDownLatch latch, long startTime,
                          long endTime){
    super(protocol, serialization, targetIP, targetPort, clientNums, rpcTimeout, barrier, latch, startTime, endTime);
    Impression imp = new Impression();
    imp.setBidFloor(1.1);
    imp.setId("abc");
    List<Impression> imps = new ArrayList<Impression>(1);
    imps.add(imp);
    request.setImpressions(imps);

    Geo geo = new Geo();
    geo.setCity("beijing");
    geo.setCountry("china");
    geo.setLat(100.1f);
    geo.setLon(100.1f);

    Device device = new Device();
    device.setMake("apple");
    device.setOs("ios");
    device.setVersion("7.0");
    device.setLang("zh_CN");
    device.setModel("iphone");
    device.setGeo(geo);
    request.setDevice(device);
}
 
Example #4
Source File: TestThreadCpuTimeEvent.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
static void testSimple() throws Throwable {
    Recording recording = new Recording();

    // Default period is once per chunk
    recording.enable(EventNames.ThreadCPULoad).withPeriod(Duration.ofMillis(eventPeriodMillis));
    recording.start();

    Duration testRunTime = Duration.ofMillis(eventPeriodMillis * cpuConsumerRunFactor);
    CyclicBarrier barrier = new CyclicBarrier(2);
    CpuConsumingThread thread = new CpuConsumingThread(testRunTime, barrier);

    // Run a single pass
    thread.start();
    barrier.await();
    barrier.await();

    recording.stop();
    List<RecordedEvent> events = Events.fromRecording(recording);

    Events.hasEvents(events);
    verifyPerThreadInvariant(events, cpuConsumerThreadName);

    thread.interrupt();
    thread.join();
}
 
Example #5
Source File: CyclicBarrierTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * A reset of an active barrier causes waiting threads to throw
 * BrokenBarrierException
 */
public void testReset_BrokenBarrier() throws InterruptedException {
    final CyclicBarrier c = new CyclicBarrier(3);
    final CountDownLatch pleaseReset = new CountDownLatch(2);
    Thread t1 = new ThreadShouldThrow(BrokenBarrierException.class) {
        public void realRun() throws Exception {
            pleaseReset.countDown();
            c.await();
        }};
    Thread t2 = new ThreadShouldThrow(BrokenBarrierException.class) {
        public void realRun() throws Exception {
            pleaseReset.countDown();
            c.await();
        }};

    t1.start();
    t2.start();
    await(pleaseReset);

    awaitNumberWaiting(c, 2);
    c.reset();
    awaitTermination(t1);
    awaitTermination(t2);
}
 
Example #6
Source File: MultipleProducersPagingTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Override
@Before
public void setUp() throws Exception {
   super.setUp();
   executor = Executors.newCachedThreadPool(ActiveMQThreadFactory.defaultThreadFactory());

   server = createServer(createBasicConfig()
                            .setPersistenceEnabled(false)
                            .setAddressesSettings(Collections.singletonMap("#", new AddressSettings()
                               .setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE)
                               .setPageSizeBytes(50000)
                               .setMaxSizeBytes(404850)))
                            .setAcceptorConfigurations(Collections.singleton(new TransportConfiguration(NettyAcceptorFactory.class.getName()))));

   server.start();

   cf = ActiveMQJMSClient.createConnectionFactory("tcp://127.0.0.1:61616", "cf");
   queue = ActiveMQJMSClient.createQueue("simple");

   barrierLatch = new CyclicBarrier(PRODUCERS + 1);
   runnersLatch = new CountDownLatch(PRODUCERS + 1);
   msgReceived = new AtomicLong(0);
   msgSent = new AtomicLong(0);
}
 
Example #7
Source File: AbstractClientRunnable.java    From dubbo-2.6.5 with Apache License 2.0 6 votes vote down vote up
public AbstractClientRunnable(String targetIP, int targetPort, int clientNums, int rpcTimeout,
                              CyclicBarrier barrier, CountDownLatch latch, long startTime, long endTime) {

    this.barrier = barrier;
    this.latch = latch;
    this.startTime = startTime;
    this.endTime = endTime;
    serviceFactory.setTargetIP(targetIP);
    serviceFactory.setClientNums(clientNums);
    serviceFactory.setTargetPort(targetPort);
    serviceFactory.setConnectTimeout(rpcTimeout);
    maxRange = (Integer.parseInt(String.valueOf((endTime - startTime))) / 1000000) + 1;
    errorTPS = new long[maxRange];
    errorResponseTimes = new long[maxRange];
    tps = new long[maxRange];
    responseTimes = new long[maxRange];
    // init
    for (int i = 0; i < maxRange; i++) {
        errorTPS[i] = 0;
        errorResponseTimes[i] = 0;
        tps[i] = 0;
        responseTimes[i] = 0;
    }
}
 
Example #8
Source File: ConnectablePayloadWriterTest.java    From servicetalk with Apache License 2.0 6 votes vote down vote up
@Test
public void subscribeCloseSynchronously() throws Exception {
    AtomicReference<Future<?>> futureRef = new AtomicReference<>();
    toSource(cpw.connect().afterOnSubscribe(subscription -> {
        // We want to increase the chance that the writer thread has to wait for the Subscriber to become
        // available, instead of waiting for the requestN demand.
        CyclicBarrier barrier = new CyclicBarrier(2);
        futureRef.compareAndSet(null, executorService.submit(toRunnable(() -> {
            barrier.await();
            cpw.close();
        })));
        try {
            barrier.await();
        } catch (InterruptedException | BrokenBarrierException e) {
            throw new RuntimeException(e);
        }
    })).subscribe(subscriber);

    Future<?> f = futureRef.get();
    assertNotNull(f);
    f.get();
    assertThat(subscriber.takeTerminal(), is(complete()));
}
 
Example #9
Source File: AbstractClientRunnable.java    From dubbox with Apache License 2.0 6 votes vote down vote up
public AbstractClientRunnable(String targetIP, int targetPort, int clientNums, int rpcTimeout,
                              CyclicBarrier barrier, CountDownLatch latch, long startTime, long endTime){

    this.barrier = barrier;
    this.latch = latch;
    this.startTime = startTime;
    this.endTime = endTime;
    serviceFactory.setTargetIP(targetIP);
    serviceFactory.setClientNums(clientNums);
    serviceFactory.setTargetPort(targetPort);
    serviceFactory.setConnectTimeout(rpcTimeout);
    maxRange = (Integer.parseInt(String.valueOf((endTime - startTime))) / 1000000) + 1;
    errorTPS = new long[maxRange];
    errorResponseTimes = new long[maxRange];
    tps = new long[maxRange];
    responseTimes = new long[maxRange];
    // init
    for (int i = 0; i < maxRange; i++) {
        errorTPS[i] = 0;
        errorResponseTimes[i] = 0;
        tps[i] = 0;
        responseTimes[i] = 0;
    }
}
 
Example #10
Source File: TestRunner.java    From IPAddress with Apache License 2.0 6 votes vote down vote up
Thread[] runInThreads(int numThreads, final Runnable runnable) {
	Thread threads[] = new Thread[numThreads];
	final CyclicBarrier barrier = new CyclicBarrier(numThreads);
	for(int i = 0; i < numThreads; i++) {
		Thread thread = new Thread() {
			@Override
			public void run() {
				try {
					barrier.await();
					runnable.run();
				} catch (InterruptedException | BrokenBarrierException e) {
					e.printStackTrace();
				}
			}
		};
		threads[i] = thread;
		thread.start();
	}
	return threads;
}
 
Example #11
Source File: MultiThreadReader.java    From JavaInterview with Apache License 2.0 6 votes vote down vote up
public void start(){
    long everySize = this.fileLength/this.threadSize;
    try {
        calculateStartEnd(0, everySize);
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }

    final long startTime = System.currentTimeMillis();
    cyclicBarrier = new CyclicBarrier(startEndPairs.size(),new Runnable() {

        @Override
        public void run() {
            System.out.println("use time: "+(System.currentTimeMillis()-startTime));
            System.out.println("all line: "+counter.get());
        }
    });
    for(StartEndPair pair:startEndPairs){
        System.out.println("分配分片:"+pair);
        this.executorService.execute(new SliceReaderTask(pair));
    }
}
 
Example #12
Source File: CyclicBarrierTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * A 2-party/thread barrier triggers after both threads invoke await
 */
public void testTwoParties() throws Exception {
    final CyclicBarrier b = new CyclicBarrier(2);
    Thread t = newStartedThread(new CheckedRunnable() {
        public void realRun() throws Exception {
            b.await();
            b.await();
            b.await();
            b.await();
        }});

    b.await();
    b.await();
    b.await();
    b.await();
    awaitTermination(t);
}
 
Example #13
Source File: CyclicBarrierTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Reset of a barrier after interruption reinitializes it.
 */
public void testResetAfterInterrupt() throws Exception {
    final CyclicBarrier barrier = new CyclicBarrier(3);
    for (int i = 0; i < 2; i++) {
        final CyclicBarrier start = new CyclicBarrier(3);
        Thread t1 = new ThreadShouldThrow(InterruptedException.class) {
            public void realRun() throws Exception {
                start.await();
                barrier.await();
            }};

        Thread t2 = new ThreadShouldThrow(BrokenBarrierException.class) {
            public void realRun() throws Exception {
                start.await();
                barrier.await();
            }};

        t1.start();
        t2.start();
        start.await();
        t1.interrupt();
        awaitTermination(t1);
        awaitTermination(t2);
        assertTrue(barrier.isBroken());
        assertEquals(0, barrier.getNumberWaiting());
        barrier.reset();
        assertFalse(barrier.isBroken());
        assertEquals(0, barrier.getNumberWaiting());
    }
}
 
Example #14
Source File: ShardConsumerTest.java    From amazon-kinesis-client with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
@Ignore
public final void testInitializationStateUponFailure() throws Exception {
    ShardConsumer consumer = new ShardConsumer(recordsPublisher, executorService, shardInfo,
            logWarningForTaskAfterMillis, shardConsumerArgument, initialState, Function.identity(), 1,
            taskExecutionListener, 0);

    when(initialState.createTask(eq(shardConsumerArgument), eq(consumer), any())).thenReturn(initializeTask);
    when(initializeTask.call()).thenReturn(new TaskResult(new Exception("Bad")));
    when(initializeTask.taskType()).thenReturn(TaskType.INITIALIZE);
    when(initialState.failureTransition()).thenReturn(initialState);

    CyclicBarrier taskBarrier = new CyclicBarrier(2);

    when(initialState.requiresDataAvailability()).thenAnswer(i -> {
        taskBarrier.await();
        return false;
    });

    consumer.executeLifecycle();
    for (int i = 0; i < 4; ++i) {
        awaitAndResetBarrier(taskBarrier);
    }

    verify(initialState, times(5)).createTask(eq(shardConsumerArgument), eq(consumer), any());
    verify(initialState, never()).successTransition();
    verify(initialState, never()).shutdownTransition(any());
}
 
Example #15
Source File: RenderWallExecutor.java    From mochadoom with GNU General Public License v3.0 5 votes vote down vote up
public Indexed(int SCREENWIDTH, int SCREENHEIGHT, int[] columnofs,
        int[] ylookup, byte[] screen,
        ColVars<byte[], byte[]>[] RWI, CyclicBarrier barrier) {
    super(SCREENWIDTH, SCREENHEIGHT, columnofs, ylookup, screen, RWI, barrier);
    colfunc =
        colfunchi =
            new R_DrawColumnBoomOpt.Indexed(SCREENWIDTH, SCREENHEIGHT, ylookup,
                    columnofs, null, screen, null);
    colfunclow =
        new R_DrawColumnBoomOptLow.Indexed(SCREENWIDTH, SCREENHEIGHT, ylookup,
                columnofs, null, screen, null);
}
 
Example #16
Source File: QuantityAttributeTestCase.java    From jstarcraft-ai with Apache License 2.0 5 votes vote down vote up
@Override
public void testConcurrent() throws Exception {
    int size = 1000;
    float[] datas = new float[size];
    for (int index = 0; index < size; index++) {
        datas[index] = index;
    }
    RandomUtility.shuffle(datas);

    final int numberOfThread = 10;
    ExecutorService executor = Executors.newFixedThreadPool(numberOfThread);
    final CyclicBarrier barrier = new CyclicBarrier(numberOfThread + 1);
    QuantityAttribute<Float> attribute = getQuantityAttribute();
    for (int thread = 0; thread < numberOfThread; thread++) {
        executor.submit(() -> {
            try {
                barrier.await();
                for (int index = 0; index < size; index++) {
                    Assert.assertEquals(datas[index], attribute.convertData(datas[index]), 0F);
                }
                Assert.assertEquals(999F, attribute.getMaximum(), 0F);
                Assert.assertEquals(0F, attribute.getMinimum(), 0F);
                barrier.await();
            } catch (Exception exception) {
                Assert.fail();
            }
        });
    }
    // 等待所有线程开始
    barrier.await();
    // 等待所有线程结束
    barrier.await();
}
 
Example #17
Source File: MemoryConflictProvoker.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public MemoryConflictProvoker(Object monitor) {
    super(monitor);
    barrier = new CyclicBarrier(2);
    conflictingThread = () -> {
        try {
            barrier.await();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        for (int i = 0; i < MemoryConflictProvoker.INNER_ITERATIONS; i++) {
            MemoryConflictProvoker.field++;
        }
    };
}
 
Example #18
Source File: ConnectablePayloadWriterTest.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
@Test
public void closeNoWrite() throws Exception {
    CyclicBarrier cb = new CyclicBarrier(2);
    Future<?> f = executorService.submit(toRunnable(() -> {
        cb.await();
        cpw.close();
    }));
    final Publisher<String> connect = cpw.connect();
    cb.await();
    toSource(connect).subscribe(subscriber);
    subscriber.request(1);
    f.get();
    assertThat(subscriber.takeItems(), is(empty()));
    assertThat(subscriber.takeTerminal(), is(complete()));
}
 
Example #19
Source File: BenchmarkClient.java    From dubbox with Apache License 2.0 5 votes vote down vote up
@Override
public ClientRunnable getClientRunnable(String targetIP, int targetPort, int clientNums, int rpcTimeout,
                                        CyclicBarrier barrier,
                                        CountDownLatch latch, long endTime, long startTime) {
    return new SimpleProcessorBenchmarkClientRunnable(targetIP, targetPort, clientNums, rpcTimeout,
                                                     barrier, latch, startTime, endTime);
}
 
Example #20
Source File: JaxwsClientCallbackTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testHandleCancellationCallback() throws Exception {
    final CyclicBarrier barrier = new CyclicBarrier(2);
    schedule(barrier, () -> callback.cancel(true));
    barrier.await(5, TimeUnit.SECONDS);

    assertThrows(InterruptedException.class, () -> callback.get());
    assertThrows(InterruptedException.class, () -> callback.get(10, TimeUnit.MILLISECONDS));
    assertThat(callback.isCancelled(), equalTo(true));
    assertThat(callback.isDone(), equalTo(true));
}
 
Example #21
Source File: QueueDrainingEventProcessorTest.java    From styx with Apache License 2.0 5 votes vote down vote up
@Test
public void processesQueuedEvents() {
    for (int i = 0; i < 1000; i++) {
        CyclicBarrier barrier1 = new CyclicBarrier(2);
        CyclicBarrier barrier2 = new CyclicBarrier(2);

        QueueDrainingEventProcessor eventProcessor = new QueueDrainingEventProcessor((event) -> ((Consumer<Void>) event).accept(null));

        Consumer<Void> event1 = mock(Consumer.class);
        Consumer<Void> event2 = mock(Consumer.class);
        Consumer<Void> event3 = mock(Consumer.class);

        startThread(() -> {
            await(barrier1);
            eventProcessor.submit(event2);
            eventProcessor.submit(event3);
            await(barrier2);
        });

        eventProcessor.submit(consumerEvent((x) -> {
            await(barrier1);
            event1.accept(null);
            await(barrier2);
        }));

        InOrder inOrder = Mockito.inOrder(event1, event2, event3);
        inOrder.verify(event1).accept(null);
        inOrder.verify(event2).accept(null);
        inOrder.verify(event3).accept(null);
    }
}
 
Example #22
Source File: SerializationDeadlock.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(final String[] args) throws Exception {
    // Test for Hashtable serialization deadlock
    final Hashtable<Object, Object> h1 = new Hashtable<>();
    final Hashtable<Object, Object> h2 = new Hashtable<>();
    final TestBarrier testStart = new TestBarrier(3);

    // Populate the hashtables so that they refer to each other
    h1.put(testStart, h2);
    h2.put(testStart, h1);

    final CyclicBarrier testEnd = new CyclicBarrier(3);
    final TestThread t1 = new TestThread(h1, testEnd);
    final TestThread t2 = new TestThread(h2, testEnd);

    t1.start();
    t2.start();

    // Wait for both test threads to have initiated serialization
    // of the 'testStart' object (and hence of both 'h1' and 'h2')
    testStart.await();

    // Wait for both test threads to successfully finish serialization
    // of 'h1' and 'h2'.
    System.out.println("Waiting for Hashtable serialization to complete ...");
    System.out.println("(This test will hang if serialization deadlocks)");
    testEnd.await();
    System.out.println("Test PASSED: serialization completed successfully");

    TestThread.handleExceptions();
}
 
Example #23
Source File: ApacheAsyncClientExecutor.java    From Thunder with Apache License 2.0 5 votes vote down vote up
public void initialize(final ThunderProperties properties) throws Exception {
    final CyclicBarrier barrier = new CyclicBarrier(2);
    Executors.newCachedThreadPool().submit(new Callable<Object>() {
        @Override
        public Object call() throws Exception {
            try {
                IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
                        .setIoThreadCount(ThunderConstant.CPUS)
                        .setConnectTimeout(properties.getInteger(ThunderConstant.APACHE_CONNECT_TIMEOUT_ATTRIBUTE_NAME))
                        .setSoTimeout(properties.getInteger(ThunderConstant.APACHE_SO_TIMEOUT_ATTRIBUTE_NAME))
                        .setSndBufSize(properties.getInteger(ThunderConstant.APACHE_SNDBUF_SIZE_ATTRIBUTE_NAME))
                        .setRcvBufSize(properties.getInteger(ThunderConstant.APACHE_RCVBUF_SIZE_ATTRIBUTE_NAME))
                        .setBacklogSize(properties.getInteger(ThunderConstant.APACHE_BACKLOG_SIZE_ATTRIBUTE_NAME))
                        .setTcpNoDelay(true)
                        .setSoReuseAddress(true)
                        .setSoKeepAlive(true)
                        .build();
                ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(ioReactorConfig);
                PoolingNHttpClientConnectionManager httpManager = new PoolingNHttpClientConnectionManager(ioReactor);
                httpManager.setMaxTotal(ThunderConstant.CPUS * properties.getInteger(ThunderConstant.APACHE_MAX_TOTAL_ATTRIBUTE_NAME));

                httpAsyncClient = HttpAsyncClients.custom().setConnectionManager(httpManager).build();
                httpAsyncClient.start();

                LOG.info("Create apache async client successfully");

                barrier.await();
            } catch (IOReactorException e) {
                LOG.error("Create apache async client failed", e);
            }

            return null;
        }
    });

    barrier.await(properties.getLong(ThunderConstant.APACHE_CONNECT_TIMEOUT_ATTRIBUTE_NAME) * 2, TimeUnit.MILLISECONDS);
}
 
Example #24
Source File: StoreStatsServiceTest.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
@Test
public void getSinglePutMessageTopicTimesTotal() throws Exception {
    final StoreStatsService storeStatsService = new StoreStatsService();
    int num = Runtime.getRuntime().availableProcessors() * 2;
    for (int j = 0; j < 100; j++) {
        final AtomicReference<AtomicLong> reference = new AtomicReference<>(null);
        final CountDownLatch latch = new CountDownLatch(num);
        final CyclicBarrier barrier = new CyclicBarrier(num);
        for (int i = 0; i < num; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        barrier.await();
                        AtomicLong atomicLong = storeStatsService.getSinglePutMessageTopicTimesTotal("test");
                        if (reference.compareAndSet(null, atomicLong)) {
                        } else if (reference.get() != atomicLong) {
                            throw new RuntimeException("Reference should be same!");
                        }
                    } catch (InterruptedException | BrokenBarrierException e) {
                        e.printStackTrace();
                    } finally {
                        latch.countDown();
                    }
                }
            }).start();
        }
        latch.await();
    }
}
 
Example #25
Source File: SerializationDeadlock.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(final String[] args) throws Exception {
    // Test for Vector serialization deadlock
    final Vector<Object> v1 = new Vector<>();
    final Vector<Object> v2 = new Vector<>();
    final TestBarrier testStart = new TestBarrier(3);

    // Populate the vectors so that they refer to each other
    v1.add(testStart);
    v1.add(v2);
    v2.add(testStart);
    v2.add(v1);

    final CyclicBarrier testEnd = new CyclicBarrier(3);
    final TestThread t1 = new TestThread(v1, testEnd);
    final TestThread t2 = new TestThread(v2, testEnd);

    t1.start();
    t2.start();

    // Wait for both test threads to have initiated serialization
    // of the 'testStart' object (and hence of both 'v1' and 'v2')
    testStart.await();

    // Wait for both test threads to successfully finish serialization
    // of 'v1' and 'v2'.
    System.out.println("Waiting for Vector serialization to complete ...");
    System.out.println("(This test will hang if serialization deadlocks)");
    testEnd.await();
    System.out.println("Test PASSED: serialization completed successfully");

    TestThread.handleExceptions();
}
 
Example #26
Source File: BenchmarkClient.java    From dubbox-hystrix with Apache License 2.0 5 votes vote down vote up
@Override
public ClientRunnable getClientRunnable(String targetIP, int targetPort, int clientNums, int rpcTimeout,
                                        CyclicBarrier barrier,
                                        CountDownLatch latch, long endTime, long startTime) {
    return new SimpleProcessorBenchmarkClientRunnable(targetIP, targetPort, clientNums, rpcTimeout,
                                                     barrier, latch, startTime, endTime);
}
 
Example #27
Source File: CyclicBarrierTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Reset of a non-broken barrier does not break barrier
 */
public void testResetWithoutBreakage() throws Exception {
    final CyclicBarrier barrier = new CyclicBarrier(3);
    for (int i = 0; i < 3; i++) {
        final CyclicBarrier start = new CyclicBarrier(3);
        Thread t1 = newStartedThread(new CheckedRunnable() {
            public void realRun() throws Exception {
                start.await();
                barrier.await();
            }});

        Thread t2 = newStartedThread(new CheckedRunnable() {
            public void realRun() throws Exception {
                start.await();
                barrier.await();
            }});

        start.await();
        barrier.await();
        awaitTermination(t1);
        awaitTermination(t2);
        assertFalse(barrier.isBroken());
        assertEquals(0, barrier.getNumberWaiting());
        if (i == 1) barrier.reset();
        assertFalse(barrier.isBroken());
        assertEquals(0, barrier.getNumberWaiting());
    }
}
 
Example #28
Source File: CheckpointInProgressRequestTest.java    From flink with Apache License 2.0 5 votes vote down vote up
private CheckpointInProgressRequest cancelCountingRequest(AtomicInteger cancelCounter, CyclicBarrier cb) {
	return new CheckpointInProgressRequest(
			"test",
			1L,
			unused -> {
			},
			unused -> {
				cancelCounter.incrementAndGet();
				await(cb);
			},
			false
	);
}
 
Example #29
Source File: SerializationDeadlock.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public static void main(final String[] args) throws Exception {
    // Test for Hashtable serialization deadlock
    final Hashtable<Object, Object> h1 = new Hashtable<>();
    final Hashtable<Object, Object> h2 = new Hashtable<>();
    final TestBarrier testStart = new TestBarrier(3);

    // Populate the hashtables so that they refer to each other
    h1.put(testStart, h2);
    h2.put(testStart, h1);

    final CyclicBarrier testEnd = new CyclicBarrier(3);
    final TestThread t1 = new TestThread(h1, testEnd);
    final TestThread t2 = new TestThread(h2, testEnd);

    t1.start();
    t2.start();

    // Wait for both test threads to have initiated serialization
    // of the 'testStart' object (and hence of both 'h1' and 'h2')
    testStart.await();

    // Wait for both test threads to successfully finish serialization
    // of 'h1' and 'h2'.
    System.out.println("Waiting for Hashtable serialization to complete ...");
    System.out.println("(This test will hang if serialization deadlocks)");
    testEnd.await();
    System.out.println("Test PASSED: serialization completed successfully");

    TestThread.handleExceptions();
}
 
Example #30
Source File: OrderedExecutorSanityTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void shutdownNowOnDelegateExecutor() throws Exception {
   final ExecutorService executorService = Executors.newSingleThreadExecutor();
   try {
      final OrderedExecutor executor = new OrderedExecutor(executorService);
      final CyclicBarrier latch = new CyclicBarrier(2);
      final AtomicInteger numberOfTasks = new AtomicInteger(0);
      final CountDownLatch ran = new CountDownLatch(1);

      executor.execute(() -> {
         try {
            latch.await(1, TimeUnit.MINUTES);
            numberOfTasks.set(executor.shutdownNow());
            ran.countDown();
         } catch (Exception e) {
            e.printStackTrace();
         }
      });


      for (int i = 0; i < 100; i++) {
         executor.execute(() -> System.out.println("Dont worry, this will never happen"));
      }

      latch.await();
      ran.await(1, TimeUnit.SECONDS);
      Assert.assertEquals(100, numberOfTasks.get());

      Assert.assertEquals(ProcessorBase.STATE_FORCED_SHUTDOWN, executor.status());
      Assert.assertEquals(0, executor.remaining());
   } finally {
      executorService.shutdown();
   }
}