Java Code Examples for java.util.concurrent.TimeUnit.MILLISECONDS

The following are Jave code examples for showing how to use MILLISECONDS of the java.util.concurrent.TimeUnit class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: java-coap   File: DuplicationDetectorTest.java   View Source Code Vote up 6 votes
@Test
public void testDuplicationWithinCleanUpTimeout() throws Exception {
    final int timeout = 300;
    final int collectionSize = 1;
    DuplicationDetector instance = new DuplicationDetector(TimeUnit.MILLISECONDS, timeout, collectionSize, Executors.newSingleThreadScheduledExecutor());
    final int cleanupInterval = 100;
    instance.setCleanDelayMili(cleanupInterval);
    instance.start();
    try {
        CoapPacket packet = mock(CoapPacket.class);
        when(packet.getRemoteAddress()).thenReturn(InetSocketAddress.createUnresolved("testHost", 8080));
        when(packet.getMessageId()).thenReturn(9);

        CoapPacket firstIsDuplicated = instance.isMessageRepeated(packet);
        Thread.sleep(cleanupInterval + 1);
        CoapPacket secondIsDuplicated = instance.isMessageRepeated(packet);

        assertNull("insertion to empty duplicate check list fails", firstIsDuplicated);
        assertNotNull("second insertion within timeout with same id succeeds", secondIsDuplicated);
    } finally {
        instance.stop();
    }
}
 
Example 2
Project: aws-sdk-java-v2   File: ApacheConnectionManagerFactory.java   View Source Code Vote up 6 votes
public HttpClientConnectionManager create(ApacheSdkHttpClientFactory configuration,
                                          AttributeMap standardOptions) {
    ConnectionSocketFactory sslsf = getPreferredSocketFactory(standardOptions);

    final PoolingHttpClientConnectionManager cm = new
            PoolingHttpClientConnectionManager(
            createSocketFactoryRegistry(sslsf),
            null,
            DefaultSchemePortResolver.INSTANCE,
            null,
            configuration.connectionTimeToLive().orElse(Defaults.CONNECTION_POOL_TTL).toMillis(),
            TimeUnit.MILLISECONDS);

    cm.setDefaultMaxPerRoute(standardOptions.get(SdkHttpConfigurationOption.MAX_CONNECTIONS));
    cm.setMaxTotal(standardOptions.get(SdkHttpConfigurationOption.MAX_CONNECTIONS));
    cm.setDefaultSocketConfig(buildSocketConfig(standardOptions));

    return cm;
}
 
Example 3
Project: storm_spring_boot_demo   File: KafkaSpout.java   View Source Code Vote up 6 votes
@Override
    public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) {
        initialized = false;
        this.context = context;

        // Spout internals
        this.collector = collector;
        numUncommittedOffsets = 0;

        // Offset management
        firstPollOffsetStrategy = kafkaSpoutConfig.getFirstPollOffsetStrategy();
        // with AutoCommitMode, offset will be periodically committed in the background by Kafka consumer
//        consumerAutoCommitMode = kafkaSpoutConfig.isConsumerAutoCommitMode();
        //永远设置为false
        consumerAutoCommitMode = false;

        // Retries management
        retryService = kafkaSpoutConfig.getRetryService();

        if (!consumerAutoCommitMode) {     // If it is auto commit, no need to commit offsets manually
            commitTimer = new Timer(TIMER_DELAY_MS, kafkaSpoutConfig.getOffsetsCommitPeriodMs(), TimeUnit.MILLISECONDS);
        }
        refreshSubscriptionTimer = new Timer(TIMER_DELAY_MS, kafkaSpoutConfig.getPartitionRefreshPeriodMs(), TimeUnit.MILLISECONDS);

        acked = new HashMap<>();
        emitted = new HashSet<>();
        waitingToEmit = Collections.emptyListIterator();

        LOG.info("Kafka Spout opened with the following configuration: {}", kafkaSpoutConfig);
    }
 
Example 4
Project: ditb   File: ProtobufUtil.java   View Source Code Vote up 6 votes
/**
 * Convert a protocol buffer TimeUnit to a client TimeUnit
 * @param proto
 * @return the converted client TimeUnit
 */
public static TimeUnit toTimeUnit(final HBaseProtos.TimeUnit proto) {
  switch (proto) {
  case NANOSECONDS:
    return TimeUnit.NANOSECONDS;
  case MICROSECONDS:
    return TimeUnit.MICROSECONDS;
  case MILLISECONDS:
    return TimeUnit.MILLISECONDS;
  case SECONDS:
    return TimeUnit.SECONDS;
  case MINUTES:
    return TimeUnit.MINUTES;
  case HOURS:
    return TimeUnit.HOURS;
  case DAYS:
    return TimeUnit.DAYS;
  default:
    throw new RuntimeException("Invalid TimeUnit " + proto);
  }
}
 
Example 5
Project: MiniDownloader   File: MiniDownloader.java   View Source Code Vote up 6 votes
/**
 * Initial MiniDownloader.
 *
 * @param context
 */
public void init(Context context) {
    this.appContext = context.getApplicationContext();
    /** Create work executor. */
    this.workExecutor = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(), Runtime.getRuntime().availableProcessors(), 0L, TimeUnit.MILLISECONDS, new PriorityBlockingQueue<Runnable>()) {
        @Override
        protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
            if (callable instanceof CustomFutureCallable) {
                return ((CustomFutureCallable) callable).newTaskFor();
            }
            return super.newTaskFor(callable);
        }
    };
    /** Create command executor. */
    this.commandExecutor = Executors.newSingleThreadExecutor();
    /** Create and initial task manager. */
    taskManager = new TaskManager();
    taskManager.init(context);
    /** Create and start ProgressUpdater. */
    progressUpdater = new ProgressUpdater();
    progressUpdater.start();
}
 
Example 6
Project: fakeload   File: AbstractFakeLoadTest.java   View Source Code Vote up 6 votes
@Test
public void testEqualsMethodReflexivity() {
    FakeLoad child1 = new SimpleFakeLoad(5, TimeUnit.SECONDS);
    FakeLoad child2 = new SimpleFakeLoad(500, TimeUnit.MILLISECONDS);
    FakeLoad child3 = new SimpleFakeLoad(1, TimeUnit.MINUTES);

    // test reflexivity
    assertEqualsReflexivity(fakeload);


    fakeload = fakeload.lasting(300, TimeUnit.MILLISECONDS).repeat(3)
            .withCpu(50)
            .withMemory(300, MemoryUnit.MB)
            .withDiskInput(5000, MemoryUnit.BYTES);
    assertEqualsReflexivity(fakeload);



    fakeload = fakeload.lasting(30, TimeUnit.SECONDS).repeat(6)
            .withCpu(80)
            .withMemory(300, MemoryUnit.KB)
            .withDiskInput(51200, MemoryUnit.BYTES)
            .addLoad(child1).addLoad(child2).addLoad(child3);
    assertEqualsReflexivity(fakeload);

}
 
Example 7
Project: Pogamut3   File: Test10_SyncAccessToInt.java   View Source Code Vote up 5 votes
@Test
public void test() {
	
	int threads = 40;
	
	ThreadPoolExecutor executor = new ThreadPoolExecutor(threads, threads, 1000, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
	
	try {
		int jobs = 1000;
		int add = 1000;
		
		latch = new CountDownLatch(jobs);
		
		for (int i = 0; i < jobs; ++i) {
			executor.execute(new IncReadDecValueAsync(add));
		}
		
		try {
			latch.await();
		} catch (InterruptedException e) {
			throw new RuntimeException("Interrupted.", e);
		}
		
		log.info("Checking value, expecting 0 ...");
		
		if (value != 0) {
			testFailed("value == " + value + " != 0");
		}
		
		testOk();
	} finally {
		executor.shutdownNow();
	}
}
 
Example 8
Project: tools   File: BlockingExecutor.java   View Source Code Vote up 5 votes
/**
 * Creates a BlockingExecutor which will block and prevent further
 * submission to the pool when the specified queue size has been reached.
 *
 * @param poolSize  the number of the threads in the pool
 * @param queueSize the size of the queue
 */
public BlockingExecutor(final int poolSize, final int queueSize) {
    super(poolSize, poolSize, 0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<Runnable>());

    // the semaphore is bounding both the number of tasks currently executing
    // and those queued up
    semaphore = new Semaphore(poolSize + queueSize);
}
 
Example 9
Project: scanning   File: _QueueControllerService.java   View Source Code Vote up 5 votes
@Override
public void init() throws EventException {
	//Configure the QueueController-EventService connector
	eventConnector = new QueueControllerEventConnector();
	eventConnector.setEventService(eservice);
	eventConnector.setUri(uri);

	resultHandler = new ExceptionHandler() {

		@Override
		public Logger getLogger() {
			return logger;
		}

	};

	//Set up requester to handle remote requests
	requester = eservice.createRequestor(uri,
			IQueueService.QUEUE_REQUEST_TOPIC,
			IQueueService.QUEUE_RESPONSE_TOPIC);

	long timeout = Long.getLong("org.eclipse.scanning.event.remote.queueControllerServiceTimeout", 5000);
    logger.debug("Setting timeout {} {}" , timeout , " ms");
	ResponseConfiguration conf = new ResponseConfiguration( ResponseType.ONE,
															timeout,
															TimeUnit.MILLISECONDS);
	requester.setResponseConfiguration(conf);
}
 
Example 10
Project: uavstack   File: MonitorAgent.java   View Source Code Vote up 5 votes
private void startMDSListenServer() {

        boolean isStartMDFListener = DataConvertHelper
                .toBoolean(this.getConfigManager().getFeatureConfiguration(this.feature, "http.enable"), false);

        if (isStartMDFListener == true) {

            // start MDFListenServer
            int port = Integer.parseInt(this.getConfigManager().getFeatureConfiguration(this.feature, "http.port"));
            int backlog = Integer
                    .parseInt(this.getConfigManager().getFeatureConfiguration(this.feature, "http.backlog"));
            int core = Integer.parseInt(this.getConfigManager().getFeatureConfiguration(this.feature, "http.core"));
            int max = Integer.parseInt(this.getConfigManager().getFeatureConfiguration(this.feature, "http.max"));
            int bqsize = Integer.parseInt(this.getConfigManager().getFeatureConfiguration(this.feature, "http.bqsize"));

            mdfListenServer = new MDFListenServer("MDFListenServer", this.feature, "mdfhandlers");

            @SuppressWarnings({ "rawtypes", "unchecked" })
            ThreadPoolExecutor exe = new ThreadPoolExecutor(core, max, 30000, TimeUnit.MILLISECONDS,
                    new ArrayBlockingQueue(bqsize));

            mdfListenServer.start(exe, port, backlog);

            if (log.isTraceEnable()) {
                log.info(this, "MDFListenServer started");
            }
        }
    }
 
Example 11
Project: Elasticsearch   File: TimeValue.java   View Source Code Vote up 4 votes
public TimeValue(long millis) {
    this(millis, TimeUnit.MILLISECONDS);
}
 
Example 12
Project: openjdk-jdk10   File: StressAddMultiThreadedTest.java   View Source Code Vote up 4 votes
public StressAddMultiThreadedTest() {
    queue = new ArrayBlockingQueue<>(THREADS);
    executor = new ThreadPoolExecutor(THREADS, THREADS, 100,
            TimeUnit.MILLISECONDS, queue,
            new ThreadPoolExecutor.CallerRunsPolicy());
}
 
Example 13
Project: apollo-custom   File: AbstractBaseIntegrationTest.java   View Source Code Vote up 4 votes
@Override
public TimeUnit appNamespaceCacheScanIntervalTimeUnit() {
  return TimeUnit.MILLISECONDS;
}
 
Example 14
Project: apollo-custom   File: DefaultConfigTest.java   View Source Code Vote up 4 votes
@Override
public TimeUnit getConfigCacheExpireTimeUnit() {
  return TimeUnit.MILLISECONDS;
}
 
Example 15
Project: azeroth   File: StandardThreadExecutor.java   View Source Code Vote up 4 votes
public StandardThreadExecutor(int coreThreads, int maxThreads, int queueCapacity,
                              ThreadFactory threadFactory) {
    this(coreThreads, maxThreads, DEFAULT_MAX_IDLE_TIME, TimeUnit.MILLISECONDS, queueCapacity,
        threadFactory);
}
 
Example 16
Project: mumu-benchmark   File: JMHSample_20_Annotations.java   View Source Code Vote up 4 votes
@Benchmark
@Warmup(iterations = 5, time = 100, timeUnit = TimeUnit.MILLISECONDS)
@Measurement(iterations = 5, time = 100, timeUnit = TimeUnit.MILLISECONDS)
public double measure() {
    return Math.log(x1);
}
 
Example 17
Project: letv   File: DefaultConfigurationFactory.java   View Source Code Vote up 4 votes
public static Executor createExecutor(int threadPoolSize, int threadPriority, QueueProcessingType tasksProcessingType) {
    return new ThreadPoolExecutor(threadPoolSize, threadPoolSize, 0, TimeUnit.MILLISECONDS, tasksProcessingType == QueueProcessingType.LIFO ? new LIFOLinkedBlockingDeque() : new LinkedBlockingQueue(), createThreadFactory(threadPriority, "uil-pool-"));
}
 
Example 18
Project: uwigem2017   File: AsyncPump.java   View Source Code Vote up 4 votes
private void buttonDispense2Pressed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonDispense2Pressed

        buttonDispense2.setEnabled(false);

        // Get the volume to dispense
        int vol = Integer.parseInt(textFieldVolume2.getText());

        // Get the speed
        int delay = Integer.parseInt(textFieldSpeed2.getText());

        // Reset the progress bar
        progressBarDispense2.setValue(0);
        progressBarDispense2.setMaximum(vol);

        // Use Executor
        ThreadPoolExecutor tpe = new ThreadPoolExecutor(4, 4, 5000, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());

        tpe.execute(new Runnable() {
            @Override
            public void run() {

                // Advance motor 
                while (progressBarDispense2.getValue() <= vol) {
                    int current = progressBarDispense2.getValue();

                    System.out.println("current = " + current);

                    progressBarDispense2.setValue(current + 1);
                    progressBarDispense2.updateUI();

                    labelVolumeDispensed2.setText(current + " / " + vol + " mL");
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(AsyncPump.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                System.out.println("Done");
                pumpTimer2.stop();
                labelVolumeDispensed2.setText("");
                buttonDispense2.setEnabled(true);
                
            }
        });

    }
 
Example 19
Project: openjdk-jdk10   File: Custom.java   View Source Code Vote up 4 votes
CustomTPE() {
    super(threadCount, threadCount,
          30, TimeUnit.MILLISECONDS,
          new ArrayBlockingQueue<Runnable>(2*threadCount));
}
 
Example 20
Project: n4js   File: StopWatchPrintUtil.java   View Source Code Vote up 2 votes
/**
 * Delegates to {@link #StopWatchPrintUtil(String, int, long, TimeUnit)} with {@link TimeUnit#MILLISECONDS} as
 * threshold unit.
 */
public StopWatchPrintUtil(String label, int tabs, long threshold) {
	this(label, tabs, threshold, TimeUnit.MILLISECONDS);
}