Example usage for java.util.concurrent CountDownLatch CountDownLatch

List of usage examples for java.util.concurrent CountDownLatch CountDownLatch

Introduction

In this page you can find the example usage for java.util.concurrent CountDownLatch CountDownLatch.

Prototype

public CountDownLatch(int count) 

Source Link

Document

Constructs a CountDownLatch initialized with the given count.

Usage

From source file:com.vmware.photon.controller.api.client.resource.VmApiTest.java

@Test
public void testGetVmAsync() throws IOException, InterruptedException {
    final Vm vm = new Vm();
    vm.setId("vm");

    ObjectMapper mapper = new ObjectMapper();
    String serialized = mapper.writeValueAsString(vm);

    setupMocks(serialized, HttpStatus.SC_OK);

    VmApi vmApi = new VmApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    vmApi.getVmAsync("foo", new FutureCallback<Vm>() {
        @Override//  ww w  .  ja  va2  s  . c o m
        public void onSuccess(@Nullable Vm result) {
            assertEquals(result, vm);
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            fail(t.toString());
            latch.countDown();
        }
    });

    assertThat(latch.await(COUNTDOWNLATCH_AWAIT_TIMEOUT, TimeUnit.SECONDS), is(true));
}

From source file:com.brienwheeler.apps.main.ContextMainTest.java

@Test
public void testShutdownInternal() throws InterruptedException {
    CountDownLatch latch = new CountDownLatch(1);
    TestContextMain main = new TestContextMain(new String[] { N, C, TestDataConstants.RMAP_CTX_CLASSPATH },
            latch);/*from   ww  w  .  j a  v  a2  s . c om*/
    TestRunner testRunner = new TestRunner(main);
    testRunner.start();

    latch.await();

    assertLaunchCount(main, 1);
    getLaunchedContext(main, 0).close();

    testRunner.join();
}

From source file:com.alibaba.otter.node.etl.common.db.DbPerfIntergration.java

@Test
public void test_stack() {
    DbMediaSource dbMediaSource = new DbMediaSource();
    dbMediaSource.setId(1L);//www.  j  a va 2 s .  c o m
    dbMediaSource.setDriver("com.mysql.jdbc.Driver");
    dbMediaSource.setUsername("otter");
    dbMediaSource.setPassword("otter");
    dbMediaSource.setUrl("jdbc:mysql://127.0.0.1:3306/retl");
    dbMediaSource.setEncode("UTF-8");
    dbMediaSource.setType(DataMediaType.MYSQL);

    DbDataMedia dataMedia = new DbDataMedia();
    dataMedia.setSource(dbMediaSource);
    dataMedia.setId(1L);
    dataMedia.setName("ljhtable1");
    dataMedia.setNamespace("otter");

    final DbDialect dbDialect = dbDialectFactory.getDbDialect(2L, dataMedia.getSource());
    want.object(dbDialect).clazIs(MysqlDialect.class);

    final TransactionTemplate transactionTemplate = dbDialect.getTransactionTemplate();

    // ??
    int minute = 5;
    int nextId = 1;
    final int thread = 10;
    final int batch = 50;
    final String sql = "insert into otter.ljhtable1 values(? , ? , ? , ?)";

    final CountDownLatch latch = new CountDownLatch(thread);
    ExecutorService executor = new ThreadPoolExecutor(thread, thread, 60, TimeUnit.SECONDS,
            new ArrayBlockingQueue(thread * 2), new NamedThreadFactory("load"),
            new ThreadPoolExecutor.CallerRunsPolicy());

    for (int sec = 0; sec < minute * 60; sec++) {
        // 
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < thread; i++) {
            final int start = nextId + i * batch;
            executor.submit(new Runnable() {

                public void run() {
                    try {
                        transactionTemplate.execute(new TransactionCallback() {

                            public Object doInTransaction(TransactionStatus status) {
                                JdbcTemplate jdbcTemplate = dbDialect.getJdbcTemplate();
                                return jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {

                                    public void setValues(PreparedStatement ps, int idx) throws SQLException {
                                        int id = start + idx;
                                        StatementCreatorUtils.setParameterValue(ps, 1, Types.INTEGER, null, id);
                                        StatementCreatorUtils.setParameterValue(ps, 2, Types.VARCHAR, null,
                                                RandomStringUtils.randomAlphabetic(1000));
                                        // RandomStringUtils.randomAlphabetic()
                                        long time = new Date().getTime();
                                        StatementCreatorUtils.setParameterValue(ps, 3, Types.TIMESTAMP,
                                                new Timestamp(time));
                                        StatementCreatorUtils.setParameterValue(ps, 4, Types.TIMESTAMP,
                                                new Timestamp(time));
                                    }

                                    public int getBatchSize() {
                                        return batch;
                                    }
                                });
                            }
                        });
                    } finally {
                        latch.countDown();
                    }
                }
            });

        }

        long endTime = System.currentTimeMillis();
        try {
            latch.await(1000 * 60L - (endTime - startTime), TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if (latch.getCount() != 0) {
            System.out.println("perf is not enough!");
            System.exit(-1);
        }
        endTime = System.currentTimeMillis();
        System.out.println("Time cost : " + (System.currentTimeMillis() - startTime));
        try {
            TimeUnit.MILLISECONDS.sleep(1000L - (endTime - startTime));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        nextId = nextId + thread * batch;
    }
    executor.shutdown();
}

From source file:com.vmware.photon.controller.nsxclient.apis.FabricApiTest.java

@Test
public void testGetFabricNode() throws IOException, InterruptedException {
    final FabricNode mockResponse = new FabricNode();
    mockResponse.setId("id");
    setupMocks(objectMapper.writeValueAsString(mockResponse), HttpStatus.SC_OK);

    FabricApi client = new FabricApi(restClient);
    final CountDownLatch latch = new CountDownLatch(1);
    client.getFabricNode("nodeId", new com.google.common.util.concurrent.FutureCallback<FabricNode>() {
        @Override/* w w  w  . j  a  v a 2  s . c o m*/
        public void onSuccess(FabricNode result) {
            assertEquals(result, mockResponse);
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            fail(t.toString());
            latch.countDown();
        }
    });

    assertThat(latch.await(COUNTDOWNLATCH_AWAIT_TIMEOUT, TimeUnit.SECONDS), is(true));
}

From source file:com.vmware.photon.controller.api.client.resource.VmRestApiTest.java

@Test
public void testGetVmAsync() throws IOException, InterruptedException {
    final Vm vm = new Vm();
    vm.setId("vm");

    ObjectMapper mapper = new ObjectMapper();
    String serialized = mapper.writeValueAsString(vm);

    setupMocks(serialized, HttpStatus.SC_OK);

    VmApi vmApi = new VmRestApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    vmApi.getVmAsync("foo", new FutureCallback<Vm>() {
        @Override/*from   w  w w  . j a va2  s  .  c  o m*/
        public void onSuccess(@Nullable Vm result) {
            assertEquals(result, vm);
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            fail(t.toString());
            latch.countDown();
        }
    });

    assertThat(latch.await(COUNTDOWNLATCH_AWAIT_TIMEOUT, TimeUnit.SECONDS), is(true));
}

From source file:ch.cyberduck.core.onedrive.OneDriveCommonsHttpRequestExecutor.java

protected Upload doUpload(final URL url, final Set<RequestHeader> headers,
        final HttpEntityEnclosingRequestBase request) {
    for (RequestHeader header : headers) {
        if (header.getKey().equals(HTTP.TRANSFER_ENCODING)) {
            continue;
        }//from   w w w . j a  va2  s. co m
        if (header.getKey().equals(HTTP.CONTENT_LEN)) {
            continue;
        }
        request.addHeader(new BasicHeader(header.getKey(), header.getValue()));
    }
    final CountDownLatch entry = new CountDownLatch(1);
    final DelayedHttpEntity entity = new DelayedHttpEntity(entry) {
        @Override
        public long getContentLength() {
            for (RequestHeader header : headers) {
                if (header.getKey().equals(HTTP.CONTENT_LEN)) {
                    return Long.valueOf(header.getValue());
                }
            }
            // Content-Encoding: chunked
            return -1L;
        }
    };
    request.setEntity(entity);
    final DefaultThreadPool executor = new DefaultThreadPool(String.format("http-%s", url), 1);
    final Future<CloseableHttpResponse> future = executor.execute(new Callable<CloseableHttpResponse>() {
        @Override
        public CloseableHttpResponse call() throws Exception {
            return client.execute(request);
        }
    });
    return new Upload() {
        @Override
        public Response getResponse() throws IOException {
            final CloseableHttpResponse response;
            try {
                response = future.get();
            } catch (InterruptedException e) {
                throw new IOException(e);
            } catch (ExecutionException e) {
                throw new IOException(e.getCause());
            } finally {
                executor.shutdown(false);
            }
            return new CommonsHttpResponse(response);
        }

        @Override
        public OutputStream getOutputStream() {
            try {
                // Await execution of HTTP request to make stream available
                entry.await();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return entity.getStream();
        }
    };
}

From source file:com.microsoft.office.core.AttachmentsAsyncTestCase.java

@Test(timeout = 60000)
public void readFileAttachmentTest() throws Exception {
    counter = new CountDownLatch(1);
    final IFileAttachment attachment = createFileAttachment();
    Futures.addCallback(Me.flushAsync(), new FutureCallback<Void>() {
        @Override//from  w  ww .  j  a va2 s. c o m
        public void onFailure(Throwable err) {
            reportError(err);
            counter.countDown();
        }

        @Override
        public void onSuccess(Void arg0) {
            try {
                checkFileAttachmentRead(attachment);
                removeAttachment(attachment);
            } catch (Exception e) {
                reportError(e);
            }
            counter.countDown();
        }
    });

    counter.await();
}

From source file:com.twotoasters.android.hoottestapplication.test.HootTest.java

@SmallTest
public void testGlobalDeserializer() {
    final CountDownLatch latch = new CountDownLatch(1);
    mHootRestClient.setGlobalDeserializer(new TestHootGlobalDeserializer());
    final HootRequest request = mHootRestClient.createRequest().get().setExpectedType(Get.class)
            .bindListener(new TestHootListener(latch, true));

    assertNotNull(request);// ww w.j  ava2  s  .c  o  m

    executeTest(request, latch);

    mHootRestClient.setGlobalDeserializer(null);

    assertTrue(request.getResult() != null && request.getResult().isSuccess()
            && request.getResult().getDeserializedResult() != null
            && ((Get) request.getResult().getDeserializedResult()).test.equals("This is a test"));
}

From source file:com.perfect.autosdk.core.JsonProxy.java

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    String addr = service.serverUrl + AddressUtil.getJsonAddr(interfaces) + '/' + method.getName();

    JsonConnection conn = new GZIPJsonConnection(addr);
    conn.setConnectTimeout(service.connectTimeoutMills);
    conn.setReadTimeout(service.readTimeoutMills);
    JsonEnvelop request = makeRequest(args[0]);
    conn.sendRequest(request);//w ww . ja  v a2 s  .co m
    JsonEnvelop<ResHeader, ?> response = conn.readResponse(ResHeader.class, method.getReturnType());
    ResHeader resHeader = response.getHeader();
    if (!resHeader.getFailures().isEmpty()) {
        if (log.isErrorEnabled()) {
            log.error("Call Error: Head info = " + resHeader + "\n" + "account info = " + service.getUsername()
                    + "\n" + "request info = " + addr + "\n" + "request param = " + args[0]);
        }
        if (resHeader.getFailures().get(0).getCode() == 8904) {
            Timer timer = new Timer("waitLock");
            final CountDownLatch latch = new CountDownLatch(1);
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    System.out.println("waiting....");
                    latch.countDown();
                }
            }, 15000);

            latch.await();
        }
    }
    ResHeaderUtil.resHeader.set(response.getHeader());
    BaiduApiQuota.setQuota(service.username, response.getHeader().getQuota());
    return response.getBody();
}

From source file:oz.hadoop.yarn.api.net.AbstractSocketHandler.java

/**
 * /*from  w w w.  j  av a2  s .c  om*/
 * @param address
 * @param server
 */
public AbstractSocketHandler(InetSocketAddress address, boolean server, Runnable onDisconnectTask) {
    Assert.notNull(address);
    this.onDisconnectTask = onDisconnectTask;
    this.address = address;
    this.executor = Executors.newCachedThreadPool();
    this.listenerTask = new ListenerTask();
    this.readingBuffer = ByteBuffer.allocate(16384);
    this.bufferPoll = new ByteBufferPool();
    try {
        this.rootChannel = server ? ServerSocketChannel.open() : SocketChannel.open();
        if (logger.isDebugEnabled()) {
            logger.debug("Created instance of " + this.getClass().getSimpleName());
        }
    } catch (Exception e) {
        throw new IllegalStateException("Failed to create an instance of the ApplicationContainerClient", e);
    }
    this.thisClass = this.getClass();
    this.lifeCycleLatch = new CountDownLatch(1);
}