Example usage for java.util.concurrent TimeUnit HOURS

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

Introduction

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

Prototype

TimeUnit HOURS

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

Click Source Link

Document

Time unit representing sixty minutes.

Usage

From source file:org.apache.hive.hcatalog.templeton.JobRequestExecutor.java

public JobRequestExecutor(JobRequestType requestType, String concurrentRequestsConfigName,
        String jobTimeoutConfigName, boolean enableCancelTask) {

    this.concurrentRequestsConfigName = concurrentRequestsConfigName;
    this.jobTimeoutConfigName = jobTimeoutConfigName;
    this.requestType = requestType;
    this.enableCancelTask = enableCancelTask;

    /*/*from  w ww. java  2 s .  co m*/
     * The default number of threads will be 0. That means thread pool is not used and
     * operation is executed with the current thread.
     */
    int threads = !StringUtils.isEmpty(concurrentRequestsConfigName)
            ? appConf.getInt(concurrentRequestsConfigName, 0)
            : 0;

    if (threads > 0) {
        /*
         * Create a thread pool with no queue wait time to execute the operation. This will ensure
         * that job requests are rejected if there are already maximum number of threads busy.
         */
        this.jobExecutePool = new ThreadPoolExecutor(threads, threads, threadKeepAliveTimeInHours,
                TimeUnit.HOURS, new SynchronousQueue<Runnable>());
        this.jobExecutePool.allowCoreThreadTimeOut(true);

        /*
         * Get the job request time out value. If this configuration value is set to 0
         * then job request will wait until it finishes.
         */
        if (!StringUtils.isEmpty(jobTimeoutConfigName)) {
            this.requestExecutionTimeoutInSec = appConf.getInt(jobTimeoutConfigName, 0);
        }

        LOG.info("Configured " + threads + " threads for job request type " + this.requestType
                + " with time out " + this.requestExecutionTimeoutInSec + " s.");
    } else {
        /*
         * If threads are not configured then they will be executed in current thread itself.
         */
        LOG.info("No thread pool configured for job request type " + this.requestType);
    }
}

From source file:org.kurento.test.metatest.BrowserCreationTest.java

private void createParallelBrowsers(int numBrowsers) throws InterruptedException {
    long startTime = System.currentTimeMillis();

    final List<Browser> browsers = Collections.synchronizedList(new ArrayList<Browser>());

    ExecutorService executor = Executors.newFixedThreadPool(numBrowsers);

    try {//from ww w.j a  v  a2s  .  c  o m

        final AbortableCountDownLatch latch = new AbortableCountDownLatch(numBrowsers);

        for (int i = 0; i < numBrowsers; i++) {

            final int numBrowser = i;

            executor.execute(new Runnable() {

                @Override
                public void run() {
                    try {

                        Browser browser = new Browser.Builder().scope(BrowserScope.DOCKER).build();

                        browsers.add(browser);

                        browser.setId("browser" + numBrowser);

                        browser.init();

                        latch.countDown();

                    } catch (Throwable t) {
                        latch.abort("Exception setting up test. A browser could not be initialised", t);
                    }
                }
            });
        }

        latch.await();

        long creationTime = System.currentTimeMillis() - startTime;

        log.debug("----------------------------------------------------------------");

        log.debug("All {} browsers started in {} millis", numBrowsers, creationTime);

        log.debug("----------------------------------------------------------------");

    } finally {

        log.debug("***************************************************************");

        startTime = System.currentTimeMillis();

        final AbortableCountDownLatch latch = new AbortableCountDownLatch(numBrowsers);

        for (final Browser browser : browsers) {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    browser.close();
                    latch.countDown();
                }
            });
        }

        executor.shutdown();
        executor.awaitTermination(10, TimeUnit.HOURS);

        latch.await();

        long destructionTime = System.currentTimeMillis() - startTime;

        log.debug("----------------------------------------------------------------");

        log.debug("All {} browsers stopped in {} millis", numBrowsers, destructionTime);

        log.debug("----------------------------------------------------------------");
    }
}

From source file:org.apache.nifi.toolkit.s2s.SiteToSiteCliMainTest.java

@Test
public void testParsePenalization() throws ParseException {
    expectedPenalizationNs = TimeUnit.HOURS.toNanos(4);
    parseAndCheckExpected(null, SiteToSiteCliMain.PENALIZATION_OPTION, "4 hours");
}

From source file:com.stratio.ingestion.sink.druid.DruidSinkIT.java

private Event getTrackerEvent() {
    Random random = new Random();
    String[] users = new String[] { "user1@santander.com", "user2@santander.com", "user3@santander.com",
            "user4@santander.com" };
    String[] isoCode = new String[] { "DE", "ES", "US", "FR" };
    TimeUnit[] offset = new TimeUnit[] { TimeUnit.DAYS, TimeUnit.HOURS, TimeUnit.SECONDS };
    ObjectNode jsonBody = new ObjectNode(JsonNodeFactory.instance);
    Map<String, String> headers;
    ObjectMapper mapper = new ObjectMapper();
    JsonNode jsonNode = null;//from   www. ja  va 2s. com
    final String fileName = "/trackerSample" + random.nextInt(4) + ".json";
    try {
        jsonNode = mapper.readTree(getClass().getResourceAsStream(fileName));
    } catch (IOException e) {
        e.printStackTrace();
    }
    headers = mapper.convertValue(jsonNode, Map.class);
    headers.put("timestamp",
            String.valueOf(new Date().getTime() + getOffset(offset[random.nextInt(3)]) * random.nextInt(100)));
    headers.put("santanderID", users[random.nextInt(4)]);
    headers.put("isoCode", isoCode[random.nextInt(4)]);

    return EventBuilder.withBody(jsonBody.toString().getBytes(Charsets.UTF_8), headers);
}

From source file:com.tinspx.util.concurrent.DelayedSemaphoreTest.java

/**
 * Test of create method, of class DelayedSemaphore.
 *///from w w  w  .  j  av  a  2  s . c  om
@Test
@SuppressWarnings("ResultOfObjectAllocationIgnored")
public void testInit() throws InterruptedException {
    new DelayedSemaphore(1, 0, null);
    DelayedSemaphore.create(1, 0);
    DelayedSemaphore.create(1, 1);

    DelayedSemaphore ls = DelayedSemaphore.create(5, 50000000);
    assertEquals(5, ls.permits());
    assertEquals(5, ls.availablePermits());
    assertEquals(50000000, ls.delay());
    assertSame(Ticker.systemTicker(), ls.ticker());
    ls.acquire(); //4
    Thread.sleep(10);
    assertEquals(5, ls.permits());
    assertEquals(4, ls.availablePermits());
    ls.acquire();//3
    ls.acquire();//2
    ls.release();//3
    assertEquals(2, ls.availablePermits());
    Thread.sleep(51);
    assertEquals(3, ls.availablePermits());
    assertEquals(5, ls.permits());

    ls.release(); //4
    ls.release();//5
    try {
        ls.release();
        fail();
    } catch (IllegalStateException ex) {
    }

    assertTrue(ls.tryAcquire(-1, TimeUnit.DAYS));
    assertTrue(ls.tryAcquire(1, -1, TimeUnit.DAYS));
    Thread.sleep(51);
    assertTrue(ls.tryAcquire(2, -1, TimeUnit.DAYS));
    assertEquals(1, ls.availablePermits(0));
    try {
        ls.release(5);
        fail();
    } catch (IllegalArgumentException ex) {
    }
    ls.release(4);
    assertEquals(5, ls.availablePermits(0));
    assertEquals(0, ls.availablePermits(TimeUnit.HOURS.toNanos(1)));

    //acquire invalid args
    try {
        ls.acquire(-1L);
        fail();
    } catch (IllegalArgumentException ex) {
    }
    try {
        ls.acquire(0);
        fail();
    } catch (IllegalArgumentException ex) {
    }
    try {
        ls.acquire(-1);
        fail();
    } catch (IllegalArgumentException ex) {
    }
    try {
        ls.acquire(0, 10);
        fail();
    } catch (IllegalArgumentException ex) {
    }
    try {
        ls.acquire(-1, 10);
        fail();
    } catch (IllegalArgumentException ex) {
    }
    try {
        ls.acquire(1, -1);
        fail();
    } catch (IllegalArgumentException ex) {
    }
    try {
        ls.acquire(2, -1);
        fail();
    } catch (IllegalArgumentException ex) {
    }

    //tryAcquire no timeout, invalid args
    try {
        ls.tryAcquire(-1L);
        fail();
    } catch (IllegalArgumentException ex) {
    }
    try {
        ls.tryAcquire(0);
        fail();
    } catch (IllegalArgumentException ex) {
    }
    try {
        ls.tryAcquire(-1);
        fail();
    } catch (IllegalArgumentException ex) {
    }
    try {
        ls.tryAcquire(0, 10);
        fail();
    } catch (IllegalArgumentException ex) {
    }
    try {
        ls.tryAcquire(-1, 10);
        fail();
    } catch (IllegalArgumentException ex) {
    }
    try {
        ls.tryAcquire(1, -1);
        fail();
    } catch (IllegalArgumentException ex) {
    }
    try {
        ls.tryAcquire(2, -1);
        fail();
    } catch (IllegalArgumentException ex) {
    }

    //tryAcquire with timeout, invalid arguments
    try {
        ls.tryAcquire(-1L, 10, TimeUnit.NANOSECONDS);
        fail();
    } catch (IllegalArgumentException ex) {
    }
    try {
        ls.tryAcquire(0, 10, TimeUnit.NANOSECONDS);
        fail();
    } catch (IllegalArgumentException ex) {
    }
    try {
        ls.tryAcquire(-1, 10, TimeUnit.NANOSECONDS);
        fail();
    } catch (IllegalArgumentException ex) {
    }
    try {
        ls.tryAcquire(0, 10, 10, TimeUnit.NANOSECONDS);
        fail();
    } catch (IllegalArgumentException ex) {
    }
    try {
        ls.tryAcquire(-1, 10, 10, TimeUnit.NANOSECONDS);
        fail();
    } catch (IllegalArgumentException ex) {
    }
    try {
        ls.tryAcquire(1, -1, 10, TimeUnit.NANOSECONDS);
        fail();
    } catch (IllegalArgumentException ex) {
    }
    try {
        ls.tryAcquire(2, -1, 10, TimeUnit.NANOSECONDS);
        fail();
    } catch (IllegalArgumentException ex) {
    }
    try {
        ls.tryAcquire(0L, 10, null);
        fail();
    } catch (NullPointerException ex) {
    }
    try {
        ls.tryAcquire(1, 10, null);
        fail();
    } catch (NullPointerException ex) {
    }
    try {
        ls.tryAcquire(2, 10, null);
        fail();
    } catch (NullPointerException ex) {
    }
    try {
        ls.tryAcquire(1, 0, 10, null);
        fail();
    } catch (NullPointerException ex) {
    }
    try {
        ls.tryAcquire(2, 0, 10, null);
        fail();
    } catch (NullPointerException ex) {
    }

    DelayedSemaphore.create(1, 0);
    try {
        DelayedSemaphore.create(0, 1);
        fail();
    } catch (IllegalArgumentException ex) {
    }
    try {
        DelayedSemaphore.create(1, -1);
        fail();
    } catch (IllegalArgumentException ex) {
    }
    try {
        DelayedSemaphore.create(1, 0, null);
        fail();
    } catch (NullPointerException ex) {
    }
}

From source file:com.netflix.conductor.dao.index.ElasticSearchDAO.java

@Inject
public ElasticSearchDAO(Client client, Configuration config, ObjectMapper om) {
    this.om = om;
    this.client = client;
    this.indexName = config.getProperty("workflow.elasticsearch.index.name", null);

    try {//from  w  w  w. j  a va  2s  . co m

        initIndex();
        updateIndexName(config);
        Executors.newScheduledThreadPool(1).scheduleAtFixedRate(() -> updateIndexName(config), 0, 1,
                TimeUnit.HOURS);

    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
}

From source file:org.apache.metron.profiler.client.window.WindowProcessorTest.java

@Test
public void testRepeatTilNow() {
    Window w = WindowProcessor.process("30 minute window every 1 hour from 3 hours ago");
    /*//  w w  w  .  ja  va 2  s  . c  o m
    A window size of 30 minutes
    Starting 3 hours ago and continuing until now
    window 1: ( now - 3 hour, now - 3 hour + 30 minutes)
    window 2: ( now - 2 hour, now - 2 hour + 30 minutes)
    window 3: ( now - 1 hour, now - 1 hour + 30 minutes)
     */
    Date now = new Date();
    List<Range<Long>> intervals = w.toIntervals(now.getTime());
    Assert.assertEquals(3, intervals.size());

    assertEquals(now.getTime() - TimeUnit.HOURS.toMillis(3), intervals.get(0).getMinimum());
    assertEquals(now.getTime() - TimeUnit.HOURS.toMillis(3) + TimeUnit.MINUTES.toMillis(30),
            intervals.get(0).getMaximum());

    assertEquals(now.getTime() - TimeUnit.HOURS.toMillis(2), intervals.get(1).getMinimum());
    assertEquals(now.getTime() - TimeUnit.HOURS.toMillis(2) + TimeUnit.MINUTES.toMillis(30),
            intervals.get(1).getMaximum());

    assertEquals(now.getTime() - TimeUnit.HOURS.toMillis(1), intervals.get(2).getMinimum());
    assertEquals(now.getTime() - TimeUnit.HOURS.toMillis(1) + TimeUnit.MINUTES.toMillis(30),
            intervals.get(2).getMaximum());
}

From source file:net.jimj.automaton.Bot.java

public void go() {
    LOGGER.debug("Creating statsCollector thread");
    Runnable collector = new Runnable() {
        @Override//from  www .  j a  v a 2  s .c  o m
        public void run() {
            JacksonDBCollection<Stats, String> statsCollection = JacksonDBCollection
                    .wrap(db.getCollection("botstats"), Stats.class, String.class);
            Stats lastStats = null;
            while (true) {
                try {
                    Stats currentStats = statsCollector.toStats();
                    //If the current stats are different or the last stats are over an hour old
                    if (!currentStats.equals(lastStats)
                            || (currentStats.getRuntimeMillis() - lastStats.getRuntimeMillis()) > TimeUnit.HOURS
                                    .toMillis(1)) {
                        statsCollection.insert(currentStats);
                        lastStats = currentStats;
                    }
                    Thread.sleep(TimeUnit.SECONDS.toMillis(15));
                } catch (InterruptedException e) {
                    //Shutting down.
                    statsCollection.insert(statsCollector.toStats());
                    break;
                } catch (MongoException me) {
                    LOGGER.error("Error in stats collection", me);
                }
            }
        }
    };
    new Thread(collector).start();
    connect();
}

From source file:com.netflix.conductor.dao.es5.index.ElasticSearch5DAO.java

@Inject
public ElasticSearch5DAO(Client client, Configuration config, ObjectMapper om) {
    this.om = om;
    this.client = client;
    this.indexName = config.getProperty("workflow.elasticsearch.index.name", null);

    try {/*from  w  w w .  java2s  .  c  om*/

        initIndex();
        updateIndexName(config);
        Executors.newScheduledThreadPool(1).scheduleAtFixedRate(() -> updateIndexName(config), 0, 1,
                TimeUnit.HOURS);

    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
}

From source file:com.linkedin.pinot.server.api.resources.ResourceTestHelper.java

public IndexSegment setupSegment(String tableName, String avroDataFilePath, String segmentNamePostfix)
        throws Exception {
    final String filePath = TestUtils.getFileFromResourceUrl(
            SegmentV1V2ToV3FormatConverter.class.getClassLoader().getResource(avroDataFilePath));

    // intentionally changed this to TimeUnit.Hours to make it non-default for testing
    final SegmentGeneratorConfig config = SegmentTestUtils.getSegmentGenSpecWithSchemAndProjectedColumns(
            new File(filePath), INDEX_DIR, "daysSinceEpoch", TimeUnit.HOURS, tableName);
    config.setSegmentNamePostfix(segmentNamePostfix);
    config.setTimeColumnName("daysSinceEpoch");
    final SegmentIndexCreationDriver driver = SegmentCreationDriverFactory.get(null);
    driver.init(config);//  www .j  a  va 2s  .  c om
    driver.build();
    File segmentDirectory = new File(INDEX_DIR, driver.getSegmentName());
    IndexSegment segment = ColumnarSegmentLoader.load(segmentDirectory, ReadMode.mmap);
    serverInstance.getInstanceDataManager().addSegment(segment.getSegmentMetadata(), null, null);
    return segment;
}