Example usage for java.util.concurrent TimeUnit MINUTES

List of usage examples for java.util.concurrent TimeUnit MINUTES

Introduction

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

Prototype

TimeUnit MINUTES

To view the source code for java.util.concurrent TimeUnit MINUTES.

Click Source Link

Document

Time unit representing sixty seconds.

Usage

From source file:locking.LockingExample.java

public static void main(String[] args) throws Exception {
    // all of the useful sample code is in ExampleClientThatLocks.java

    // FakeLimitedResource simulates some external resource that can only be access by one process at a time
    final FakeLimitedResource resource = new FakeLimitedResource();

    ExecutorService service = Executors.newFixedThreadPool(QTY);
    final TestingServer server = new TestingServer();
    try {/*from www. j av a2 s.c  o  m*/
        for (int i = 0; i < QTY; ++i) {
            final int index = i;
            Callable<Void> task = new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
                            new ExponentialBackoffRetry(1000, 3));
                    try {
                        client.start();

                        ExampleClientThatLocks example = new ExampleClientThatLocks(client, PATH, resource,
                                "Client " + index);
                        for (int j = 0; j < REPETITIONS; ++j) {
                            example.doWork(10, TimeUnit.SECONDS);
                        }
                    } catch (Throwable e) {
                        e.printStackTrace();
                    } finally {
                        IOUtils.closeQuietly(client);
                    }
                    return null;
                }
            };
            service.submit(task);
        }

        service.shutdown();
        service.awaitTermination(10, TimeUnit.MINUTES);
    } finally {
        IOUtils.closeQuietly(server);
    }
}

From source file:ch.rasc.wampspring.demo.client.CallClientSockJs.java

public static void main(String[] args) throws InterruptedException {

    List<Transport> transports = new ArrayList<>(2);
    transports.add(new WebSocketTransport(new StandardWebSocketClient()));
    transports.add(new RestTemplateXhrTransport());
    WebSocketClient webSocketClient = new SockJsClient(transports);

    JsonFactory jsonFactory = new MappingJsonFactory(new ObjectMapper());

    CountDownLatch latch = new CountDownLatch(10_000);
    TestTextWebSocketHandler handler = new TestTextWebSocketHandler(jsonFactory, latch);

    Long[] start = new Long[1];
    ListenableFuture<WebSocketSession> future = webSocketClient.doHandshake(handler,
            "ws://localhost:8080/wampOverSockJS");
    future.addCallback(wss -> {//www .  java 2s.c om
        start[0] = System.currentTimeMillis();
        for (int i = 0; i < 10_000; i++) {

            CallMessage callMessage = new CallMessage(UUID.randomUUID().toString(), "testService.sum", i,
                    i + 1);
            try {
                wss.sendMessage(new TextMessage(callMessage.toJson(jsonFactory)));
            } catch (Exception e) {
                System.out.println("ERROR SENDING CALLMESSAGE" + e);
                latch.countDown();
            }
        }

    }, t -> {
        System.out.println("DO HANDSHAKE ERROR: " + t);
        System.exit(1);
    });

    if (!latch.await(3, TimeUnit.MINUTES)) {
        System.out.println("SOMETHING WENT WRONG");
    }

    System.out.println((System.currentTimeMillis() - start[0]) / 1000 + " seconds");
    System.out.println("SUCCESS: " + handler.getSuccess());
    System.out.println("ERROR  : " + handler.getError());
}

From source file:io.kahu.hawaii.util.call.example.Example1.java

public static final void main(String[] args) throws Exception {
    DOMConfigurator.configure(Example1.class.getResource("/log4j.xml").getFile());

    RestServer server = null;//from  w  w w .j  ava2 s . c o  m
    ExecutorRepository executorRepository = null;
    try {
        /*
         * Create our rest server with a 'ClientResource'.
         */
        server = new RestServer(SERVER_PORT);
        server.addResource(ClientResource.class);
        server.start();

        /*
         * Dispatcher Framework setup
         */
        // Create a log manager (purpose and explanation out of scope for this example).
        LogManager logManager = new DefaultLogManager(new LogManagerConfiguration(new LoggingConfiguration()));

        // Create an executor, with a thread pool of core size 1 and max size 2 and with a queue of size 4.
        // Threads 'outside the core pool' that are still active after one minute will get cleaned up.
        HawaiiExecutorImpl executor = new HawaiiExecutorImpl(ExecutorRepository.DEFAULT_EXECUTOR_NAME, 1, 2, 4,
                new TimeOut(1, TimeUnit.MINUTES), logManager);

        // Create the repository that holds all executors
        executorRepository = new ExecutorRepository(logManager);
        executorRepository.add(executor);

        // Create a new request dispatcher.
        RequestDispatcher requestDispatcher = new RequestDispatcher(executorRepository, logManager);

        /*
         * Setup the request (builder).
         */
        HttpRequestContext<Person> context = new HttpRequestContext<>(HttpMethod.GET,
                "http://localhost:" + SERVER_PORT, "/customer/{customer-id}", "crm", "get_customer_by_id",
                new TimeOut(2, TimeUnit.SECONDS));
        CallLogger callLogger = new CallLoggerImpl<>(logManager, new HttpRequestLogger(),
                new JsonPayloadResponseLogger<Person>());
        RequestPrototype<HttpResponse, Person> prototype = new RequestPrototype(requestDispatcher, context,
                new GetCustomerByIdResponseHandler(), callLogger);
        HttpRequestBuilder<Person> getCustomerByIdRequest = new HttpRequestBuilder<>(prototype);

        /*
         * Use the request (builder).
         */
        Request<Person> request = getCustomerByIdRequest.newInstance().withPathVariables("10").build();
        Person person = request.execute().get();

        System.err
                .println("CLIENT - Got customer '" + person.getName() + "' with id '" + person.getId() + "'.");

    } finally {
        server.stop();
        if (executorRepository != null) {
            executorRepository.stop();
        }
    }

}

From source file:io.kahu.hawaii.util.call.example.Example2.java

public static final void main(String[] args) throws Exception {
    DOMConfigurator.configure(Example2.class.getResource("/log4j.xml").getFile());

    RestServer server = null;/*from  w  w  w .j a  v a  2 s  . c  o m*/
    ExecutorRepository executorRepository = null;
    try {
        /*
         * Create our rest server with a 'ClientResource'.
         */
        server = new RestServer(SERVER_PORT);
        server.addResource(ClientResource.class);
        server.start();

        /*
         * START of generic setup
         */
        // Create a log manager (purpose and explanation out of scope for this example).
        LogManager logManager = new DefaultLogManager(new LogManagerConfiguration(new LoggingConfiguration()));

        // Create an executor, which holds a queue with core size 1, max size 2, a queue of size 2. Threads 'outside the core pool' that are still active after one minute will get cleaned up.
        HawaiiExecutorImpl executor = new HawaiiExecutorImpl(ExecutorRepository.DEFAULT_EXECUTOR_NAME, 1, 2, 2,
                new TimeOut(1, TimeUnit.MINUTES), logManager);
        // Create an executor, which holds a queue with core size 1, max size 2, a queue of size 2. Threads 'outside the core pool' that are still active after one minute will get cleaned up.
        HawaiiExecutorImpl executor2 = new HawaiiExecutorImpl("crm", 1, 2, 2, new TimeOut(1, TimeUnit.MINUTES),
                logManager);

        // Create the repository that holds all executors
        executorRepository = new ExecutorRepository(logManager);
        executorRepository.add(executor);
        executorRepository.add(executor2);

        Map<String, String> defaultExecutors = new HashMap<>();
        defaultExecutors.put("crm", "crm");
        executorRepository.setDefaultExecutors(defaultExecutors);

        // Create a new request dispatcher.
        RequestDispatcher requestDispatcher = new RequestDispatcher(executorRepository, logManager);

        /*
         * END of generic setup
         */

        /*
         * Setup the request (builder).
         */
        HttpRequestContext<Person> context = new HttpRequestContext<>(HttpMethod.GET,
                "http://localhost:" + SERVER_PORT, "/client/{client-id}", "crm", "get_client_by_id",
                new TimeOut(10, TimeUnit.SECONDS));
        CallLogger callLogger = new CallLoggerImpl<>(logManager, new HttpRequestLogger(),
                new JsonPayloadResponseLogger<Person>());
        RequestPrototype<HttpResponse, Person> prototype = new RequestPrototype(requestDispatcher, context,
                new GetCustomerByIdResponseHandler(), callLogger);
        HttpRequestBuilder<Person> getPersonByIdRequest = new HttpRequestBuilder<>(prototype);

        /*
         * Use the request (builder).
         */
        Request<Person> request = getPersonByIdRequest.newInstance().withPathVariables("10").build();
        Person person = request.execute().get();

        System.err.println("CLIENT - Got client '" + person.getName() + "' with id '" + person.getId() + "'.");

    } finally {
        server.stop();
        if (executorRepository != null) {
            executorRepository.stop();
        }
    }

}

From source file:ch.rasc.wampspring.demo.client.Publisher.java

public static void main(String[] args) throws InterruptedException {

    WebSocketClient webSocketClient = new StandardWebSocketClient();
    final JsonFactory jsonFactory = new MappingJsonFactory(new ObjectMapper());

    final CountDownLatch welcomeLatch = new CountDownLatch(1);
    final CountDownLatch latch = new CountDownLatch(1_000_000);
    TextWebSocketHandler handler = new TextWebSocketHandler() {

        @Override//  ww w.jav  a 2  s . co m
        protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
            WampMessage wampMessage = WampMessage.fromJson(jsonFactory, message.getPayload());

            if (wampMessage instanceof WelcomeMessage) {
                latch.countDown();
            }

        }

    };

    Long[] start = new Long[1];
    ListenableFuture<WebSocketSession> future = webSocketClient.doHandshake(handler,
            "ws://localhost:8080/wamp");
    future.addCallback(wss -> {

        // Waiting for WELCOME message
        try {
            welcomeLatch.await(5, TimeUnit.SECONDS);

            start[0] = System.currentTimeMillis();
            for (int i = 0; i < 1_000_000; i++) {
                PublishMessage publishMessage = new PublishMessage("/test/myqueue", i);
                try {
                    wss.sendMessage(new TextMessage(publishMessage.toJson(jsonFactory)));
                } catch (Exception e) {
                    System.out.println("ERROR SENDING PUBLISH_MESSAGE" + e);
                }
                latch.countDown();
            }

        } catch (Exception e1) {
            System.out.println("SENDING PUBLISH MESSAGES: " + e1);
        }

    }, t -> {
        System.out.println("DO HANDSHAKE ERROR: " + t);
        System.exit(1);
    });

    if (!latch.await(3, TimeUnit.MINUTES)) {
        System.out.println("SOMETHING WENT WRONG");
    }
    System.out.println((System.currentTimeMillis() - start[0]) / 1000 + " seconds");
}

From source file:de.meldanor.autothesis.Core.java

public static void main(String[] args) {
    try {//  w w w .j a v a2  s  .c  o m
        AutoThesisCommandOption options = AutoThesisCommandOption.getInstance();
        CommandLine commandLine = new GnuParser().parse(options, args);

        // Missing commands
        if (!commandLine.hasOption(options.getUserCommand())
                || !commandLine.hasOption(options.getTokenCommand())
                || !commandLine.hasOption(options.getRepoCommand())) {
            new HelpFormatter().printHelp("autothesis", options);
            return;
        }

        String user = commandLine.getOptionValue(options.getUserCommand());
        String repo = commandLine.getOptionValue(options.getRepoCommand());
        String token = commandLine.getOptionValue(options.getTokenCommand());

        logger.info("Hello World, this is AutoThesis!");
        long intervalMinutes = Long.parseLong(commandLine.getOptionValue(options.getIntervalCommand(), "60"));
        logger.info("Check for update interval: " + intervalMinutes + " min");
        final AutoThesis autoThesis = new AutoThesis(user, repo, token);
        Executors.newScheduledThreadPool(1).scheduleAtFixedRate(() -> {
            try {
                autoThesis.execute();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }, 0, intervalMinutes, TimeUnit.MINUTES);

    } catch (Exception e) {
        logger.throwing(Level.ERROR, e);
    }
}

From source file:com.pinterest.pinlater.PinLaterServer.java

public static void main(String[] args) {
    try {/*from ww  w . j  a  va 2 s.  c  o m*/
        String serverHostName = InetAddress.getLocalHost().getHostName();
        PinLaterQueueConfig queueConfig = new PinLaterQueueConfig(CONFIGURATION);
        queueConfig.initialize();
        String backend = CONFIGURATION.getString("PINLATER_BACKEND");
        PinLaterBackendIface backendIFace = getBackendIface(backend, serverHostName);
        PinLaterServiceImpl serviceImpl = new PinLaterServiceImpl(backendIFace, queueConfig);
        PinLater.Service service = new PinLater.Service(serviceImpl, new TBinaryProtocol.Factory());
        ServiceShutdownHook.register(ServerBuilder.safeBuild(service,
                ServerBuilder.get().name("PinLaterService").codec(ThriftServerFramedCodec.get())
                        .hostConnectionMaxIdleTime(Duration.fromTimeUnit(
                                CONFIGURATION.getInt("SERVER_CONN_MAX_IDLE_TIME_MINUTES"), TimeUnit.MINUTES))
                        .maxConcurrentRequests(CONFIGURATION.getInt("MAX_CONCURRENT_REQUESTS"))
                        .reportTo(new OstrichStatsReceiver(Stats.get("")))
                        .bindTo(new InetSocketAddress(CONFIGURATION.getInt("THRIFT_PORT")))));
        new OstrichAdminService(CONFIGURATION.getInt("OSTRICH_PORT")).start();

        LOG.info("\n#######################################" + "\n#      Ready To Serve Requests.       #"
                + "\n#######################################");
    } catch (Exception e) {
        LOG.error("Failed to start the pinlater server", e);
        System.exit(1);
    }
}

From source file:com.yahoo.athenz.example.instance.InstanceClientRegister.java

public static void main(String[] args) throws MalformedURLException, IOException {

    // parse our command line to retrieve required input

    CommandLine cmd = parseCommandLine(args);

    String domainName = cmd.getOptionValue("domain").toLowerCase();
    String serviceName = cmd.getOptionValue("service").toLowerCase();
    String provider = cmd.getOptionValue("provider").toLowerCase();
    String instance = cmd.getOptionValue("instance");
    String dnsSuffix = cmd.getOptionValue("dnssuffix");
    String providerKeyPath = cmd.getOptionValue("providerkey");
    String providerKeyId = cmd.getOptionValue("providerkeyid");
    String instanceKeyPath = cmd.getOptionValue("instancekey");
    String ztsUrl = cmd.getOptionValue("ztsurl");

    // get our configured private key

    PrivateKey providerKey = Crypto.loadPrivateKey(new File(providerKeyPath));

    // first we are going to generate our attestation data
    // which we are going to use jwt. ZTS Server will send
    // this object to the specified provider for validation

    String compactJws = Jwts.builder().setSubject(domainName + "." + serviceName).setIssuer(provider)
            .setAudience("zts").setId(instance)
            .setExpiration(/*from ww  w  .  j  a  va  2s  . c om*/
                    new Date(System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(5, TimeUnit.MINUTES)))
            .setHeaderParam("keyId", providerKeyId).signWith(SignatureAlgorithm.RS256, providerKey).compact();

    System.out.println("JWS: \n" + compactJws + "\n");

    // now we need to generate our CSR so we can get
    // a TLS certificate for our instance

    PrivateKey instanceKey = Crypto.loadPrivateKey(new File(instanceKeyPath));
    String csr = generateCSR(domainName, serviceName, instance, dnsSuffix, instanceKey);

    if (csr == null) {
        System.err.println("Unable to generate CSR for instance");
        System.exit(1);
    }
    System.out.println("CSR: \n" + csr + "\n");

    // now let's generate our instance register object that will be sent
    // to the ZTS Server

    InstanceRegisterInformation info = new InstanceRegisterInformation().setAttestationData(compactJws)
            .setDomain(domainName).setService(serviceName).setProvider(provider).setToken(true).setCsr(csr);

    // now contact zts server to request identity for instance

    InstanceIdentity identity = null;
    Map<String, List<String>> responseHeaders = new HashMap<>();
    try (ZTSClient ztsClient = new ZTSClient(ztsUrl)) {
        identity = ztsClient.postInstanceRegisterInformation(info, responseHeaders);
    } catch (ZTSClientException ex) {
        System.out.println("Unable to register instance: " + ex.getMessage());
        System.exit(2);
    }

    System.out.println("Identity TLS Certificate: \n" + identity.getX509Certificate());
    Map<String, String> attrs = identity.getAttributes();
    if (attrs != null) {
        System.out.println("Provider Attributes:");
        for (String key : attrs.keySet()) {
            System.out.println("\t" + key + ": " + attrs.get(key));
        }
    }
}

From source file:com.easarrive.aws.plugins.common.service.impl.SimpleProducerConsumer.java

public static void main(String[] args) throws InterruptedException {
    final AWSCredentials credentials = new BasicAWSCredentials("AKIAIDPJMKK4UHLE3OVA",
            "A+cn+TT3tUs6xbto5k1IKkWwPLBq995aOkqKxZNY");

    final String endpoint = "sqs.us-west-2.amazonaws.com";
    final String queueName = "image";
    final int producerCount = 10;
    final int consumerCount = 3;
    final int batchSize = 3;
    final int messageSizeByte = 10000;
    final int runTimeMinutes = 100;

    // configure the SQS client with enough connections for all producer and
    // consumer threads
    AmazonSQS sqsClient = new AmazonSQSClient(credentials,
            new ClientConfiguration().withMaxConnections(producerCount + consumerCount));
    sqsClient.setEndpoint(endpoint);/*  w ww  .  ja va2  s  .c om*/
    String queueUrl = sqsClient.getQueueUrl(new GetQueueUrlRequest(queueName)).getQueueUrl();

    // the flag to stop producer, consumer, and monitor threads
    AtomicBoolean stop = new AtomicBoolean(false);

    // start the producers
    final AtomicInteger producedCount = new AtomicInteger();
    Thread[] producers = new Thread[producerCount];
    for (int i = 0; i < producerCount; i++) {
        producers[i] = new BatchProducer(sqsClient, queueUrl, batchSize, messageSizeByte, producedCount, stop);
        producers[i].start();
    }

    // start the consumers
    final AtomicInteger consumedCount = new AtomicInteger();
    Thread[] consumers = new Thread[consumerCount];
    for (int i = 0; i < consumerCount; i++) {
        consumers[i] = new BatchConsumer(sqsClient, queueUrl, batchSize, consumedCount, stop);
        consumers[i].start();
    }

    // start the monitor (thread)
    Thread monitor = new Monitor(producedCount, consumedCount, stop);
    monitor.start();

    // wait for the specified amount of time then stop
    Thread.sleep(TimeUnit.MINUTES.toMillis(Math.min(runTimeMinutes, MAX_RUNTIME_MINUTES)));
    stop.set(true);

    // join all threads
    for (int i = 0; i < producerCount; i++)
        producers[i].join();

    for (int i = 0; i < consumerCount; i++)
        consumers[i].join();

    monitor.interrupt();
    monitor.join();
}

From source file:com.ciphertool.zodiacengine.CipherSolutionExecutor.java

/**
 * @param args//from  ww  w .  j  a v a2 s.c  o m
 * @throws InterruptedException
 */
public static void main(String[] args) throws InterruptedException {
    // Spin up the Spring application context
    setUp();

    CipherDto cipherDto = null;

    Cipher cipher = cipherDao.findByCipherName(cipherName);

    long start = System.currentTimeMillis();

    ExecutorService executor = Executors.newFixedThreadPool(maxThreads);

    cipherDto = new CipherDto(String.valueOf(0), cipher);

    /*
     * We want to generate and validate a specific number of solutions, no
     * matter how long it takes.
     */
    if (applicationDurationType == ApplicationDurationType.ITERATION) {
        if (numIterations <= 0) {
            throw new IllegalArgumentException(
                    "ApplicationDurationType set to ITERATION, but numIterations was not set or was set incorrectly.");
        }

        log.info("Beginning solution generation.  Generating " + numIterations + " solutions using "
                + maxThreads + " threads.");

        for (long i = 1; i <= numIterations; i++) {
            Runnable cipherTask = new CipherSolutionSynchronizedRunnable(solutionGenerator, solutionEvaluator,
                    cipherDto);

            executor.execute(cipherTask);
        }

        // Make executor accept no new threads and finish all existing
        // threads in the queue
        executor.shutdown();
    }
    /*
     * We want to generate and validate solutions for a set amount of time,
     * no matter how many we can generate in that time period.
     */
    else if (applicationDurationType == ApplicationDurationType.TEMPORAL) {
        if (applicationRunMillis <= 0) {
            throw new IllegalArgumentException(
                    "ApplicationDurationType set to TEMPORAL, but applicationRunMillis was not set or was set incorrectly.");
        }

        log.info("Beginning solution generation.  Generating solutions for " + applicationRunMillis
                + "ms using " + maxThreads + " threads.");

        long count = 0;

        while (true) {
            Runnable cipherTask = new CipherSolutionSynchronizedRunnable(solutionGenerator, solutionEvaluator,
                    cipherDto);

            executor.execute(cipherTask);

            /*
             * This is a fairly rudimentary way of managing the number of
             * tasks sent to the executor.
             * 
             * If we don't manage it somehow, the app will get bogged down
             * by the continuous while loop and performance will degrade
             * significantly.
             */
            if (++count >= queueTaskLimit) {
                count = 0;

                executor.shutdown();

                /*
                 * We are mainly concerned about blocking until all tasks
                 * are finished, so the timeout is not a big concern.
                 */
                executor.awaitTermination(1, TimeUnit.MINUTES);

                executor = Executors.newFixedThreadPool(maxThreads);

                if ((System.currentTimeMillis() - start) > applicationRunMillis) {
                    break;
                }
            }
        }

        // Make executor stop immediately
        executor.shutdownNow();
    }

    // Wait until all threads are finished
    while (!executor.isTerminated()) {
    }

    SolutionChromosome solutionMostMatches = cipherDto.getSolutionMostMatches();
    SolutionChromosome solutionMostUnique = cipherDto.getSolutionMostUnique();
    SolutionChromosome solutionMostAdjacent = cipherDto.getSolutionMostAdjacent();

    /*
     * Print out summary information
     */
    log.info("Took " + (System.currentTimeMillis() - start) + "ms to generate and validate "
            + cipherDto.getNumSolutions() + " solutions.");
    log.info("Highest total matches achieved: " + solutionMostMatches.getTotalMatches());
    log.info("Average total matches: " + (cipherDto.getTotalMatchSum() / cipherDto.getNumSolutions()));
    log.info("Best solution found: " + solutionMostMatches);
    log.info("Most unique matches achieved: " + solutionMostUnique.getUniqueMatches());
    log.info("Average unique matches: " + (cipherDto.getUniqueMatchSum() / cipherDto.getNumSolutions()));
    log.info("Solution with most unique matches found: " + solutionMostUnique);
    log.info("Most adjacent matches achieved: " + solutionMostAdjacent.getAdjacentMatchCount());
    log.info("Average adjacent matches: " + (cipherDto.getAdjacentMatchSum() / cipherDto.getNumSolutions()));
    log.info("Solution with most adjacent matches found: " + solutionMostAdjacent);
}