Java Code Examples for java.util.concurrent.TimeUnit

The following are top voted examples for showing how to use java.util.concurrent.TimeUnit. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: ditb   File: TestIdLock.java   View source code 8 votes vote down vote up
@Test
public void testMultipleClients() throws Exception {
  ExecutorService exec = Executors.newFixedThreadPool(NUM_THREADS);
  try {
    ExecutorCompletionService<Boolean> ecs =
        new ExecutorCompletionService<Boolean>(exec);
    for (int i = 0; i < NUM_THREADS; ++i)
      ecs.submit(new IdLockTestThread("client_" + i));
    for (int i = 0; i < NUM_THREADS; ++i) {
      Future<Boolean> result = ecs.take();
      assertTrue(result.get());
    }
    idLock.assertMapEmpty();
  } finally {
    exec.shutdown();
    exec.awaitTermination(5000, TimeUnit.MILLISECONDS);
  }
}
 
Example 2
Project: auto-scale-java   File: OKHttpUtil.java   View source code 7 votes vote down vote up
public static synchronized OKHttpUtil getInstance(){
        ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
                .tlsVersions(TlsVersion.TLS_1_2)
                .cipherSuites(
                        CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
                        CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
                        CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256)
                .build();
        client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
//                .connectionSpecs(Collections.singletonList(spec)).
                .addInterceptor(new RetryInterceptor())
                .build();
        return INSTANCE;
    }
 
Example 3
Project: orange-mathoms-logging   File: ThreadPoolTaskExecutorWithMdcPropagationTest.java   View source code 6 votes vote down vote up
@Test
	public void mdc_context_should_be_propagated() throws InterruptedException, ExecutionException {
//		ExecutorService executorService = Executors.newFixedThreadPool(4);
		ExecutorService executorService = new ThreadPoolTaskExecutorWithMdcPropagation(4, 4, 50, TimeUnit.MILLISECONDS, new LinkedBlockingQueue());
		List<Future<String>> futures = new ArrayList<Future<String>>();
		List<String> expectedTasks = new ArrayList<>();
		for(int i=0; i<100; i++) {
			MDC.put("requestId", "task"+i);
			expectedTasks.add("task"+i);
			futures.add(executorService.submit(new Callable<String>() {
				@Override
				public String call() throws Exception {
					Thread.sleep(100);
					return MDC.get("requestId");
				}
			}));
		}
		
		for(Future<String> f : futures) {
			String t = f.get();
			if(!expectedTasks.remove(t)) {
				Assert.fail("Unexpected task: "+t);
			}
		}
		if(!expectedTasks.isEmpty()) {
			Assert.fail("Expected tasks not returned: "+expectedTasks);
		}
	}
 
Example 4
Project: config   File: SimpleConfigPropertyTest.java   View source code 6 votes vote down vote up
@Test
public void testValueParserFailingOnReload() throws Exception {
  when(configSource.loadConfig())
      .thenReturn(toConfigProps(mapBuilder().put("int", "1").build()))
      .thenReturn(toConfigProps(mapBuilder().put("int", "not an int").build()));
  ConfigRegistryImpl configRegistry = newConfigRegistry(configSource);

  IntConfigProperty intProperty = configRegistry.intProperty("int");
  intProperty.addValidator(Objects::nonNull);
  intProperty.addValidator(i -> i >= 1);
  intProperty.addCallback((i1, i2) -> sideEffect.apply(i1, i2));

  assertTrue(intProperty.value().isPresent());
  assertEquals(1, (int) intProperty.value().get());

  TimeUnit.MILLISECONDS.sleep(WAIT_FOR_RELOAD_PERIOD_MILLIS);

  assertTrue(intProperty.value().isPresent());
  assertEquals(1, (int) intProperty.value().get());
  verify(sideEffect, never()).apply(any(), any());
}
 
Example 5
Project: lams   File: SimpleNonceManager.java   View source code 6 votes vote down vote up
private boolean addInvalidNonce(final Nonce nonce, final XnioExecutor executor) {
    long now = System.currentTimeMillis();
    long invalidBefore = now - firstUseTimeOut;

    long timeTillInvalid = nonce.timeStamp - invalidBefore;
    if (timeTillInvalid > 0) {
        if (invalidNonces.add(nonce.nonce)) {
            executor.executeAfter(new InvalidNonceCleaner(nonce.nonce), timeTillInvalid, TimeUnit.MILLISECONDS);
            return true;
        } else {
            return false;
        }
    } else {
        // So close to expiring any record of this nonce being used could have been cleared so
        // don't take a chance and just say no.
        return false;
    }
}
 
Example 6
Project: Dalaran   File: XApiServiceHelper.java   View source code 6 votes vote down vote up
public static   <T> T create(Class<T> c, String url) {
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient client = new OkHttpClient.Builder()
            .addInterceptor(interceptor)//日志拦截器
            .addNetworkInterceptor(new CommonInterceptor())//网络拦截器,进行重定向等操作
            .connectTimeout(10, TimeUnit.SECONDS)//设置连接超时
            .build();
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(url)
            .addConverterFactory(XJsonConverterFactory.create())//json数据转换
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//将Callable接口转换成Observable接口
            .client(client)//网络请求客户端为okhttp
            .build();
    return retrofit.create(c);
}
 
Example 7
Project: drinkwater-java   File: Main.java   View source code 6 votes vote down vote up
protected void waitUntilCompleted() {
    while (!completed.get()) {
        try {
            if (duration > 0) {
                TimeUnit unit = getTimeUnit();
                LOG.info("Waiting for: " + duration + " " + unit);
                latch.await(duration, unit);
                exitCode.compareAndSet(UNINITIALIZED_EXIT_CODE, durationHitExitCode);
                completed.set(true);
            } else {
                latch.await();
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}
 
Example 8
Project: GitHub   File: CacheTest.java   View source code 6 votes vote down vote up
@Test public void requestPragmaNoCache() throws Exception {
  server.enqueue(new MockResponse()
      .addHeader("Last-Modified: " + formatDate(-120, TimeUnit.SECONDS))
      .addHeader("Date: " + formatDate(0, TimeUnit.SECONDS))
      .addHeader("Cache-Control: max-age=60")
      .setBody("A"));
  server.enqueue(new MockResponse()
      .setBody("B"));

  HttpUrl url = server.url("/");
  assertEquals("A", get(url).body().string());
  Request request = new Request.Builder()
      .url(url)
      .header("Pragma", "no-cache")
      .build();
  Response response = client.newCall(request).execute();
  assertEquals("B", response.body().string());
}
 
Example 9
Project: iTAP-controller   File: SwitchResourceBase.java   View source code 6 votes vote down vote up
protected OFFeaturesReply getSwitchFeaturesReply(DatapathId switchId) {
	IOFSwitchService switchService =
			(IOFSwitchService) getContext().getAttributes().
			get(IOFSwitchService.class.getCanonicalName());

	IOFSwitch sw = switchService.getSwitch(switchId);
	Future<OFFeaturesReply> future;
	OFFeaturesReply featuresReply = null;
	OFFeaturesRequest featuresRequest = sw.getOFFactory().buildFeaturesRequest().build();
	if (sw != null) {
		try {
			future = sw.writeRequest(featuresRequest);
			featuresReply = future.get(10, TimeUnit.SECONDS);
		} catch (Exception e) {
			log.error("Failure getting features reply from switch" + sw, e);
		}
	}

	return featuresReply;
}
 
Example 10
Project: neoscada   File: Activator.java   View source code 6 votes vote down vote up
@Override
public void start ( final BundleContext bundleContext ) throws Exception
{
    this.executor = new ExportedExecutorService ( "org.eclipse.scada.ca.server.osgi", 1, 1, 1, TimeUnit.MINUTES );

    Activator.context = bundleContext;
    this.tracker = new SingleServiceTracker<ConfigurationAdministrator> ( bundleContext, ConfigurationAdministrator.class, new SingleServiceListener<ConfigurationAdministrator> () {

        @Override
        public void serviceChange ( final ServiceReference<ConfigurationAdministrator> reference, final ConfigurationAdministrator service )
        {
            setService ( service );
        }
    } );
    this.tracker.open ();
}
 
Example 11
Project: rocketmq-rocketmq-all-4.1.0-incubating   File: ConsumeMessageOrderlyService.java   View source code 6 votes vote down vote up
private void submitConsumeRequestLater(//
    final ProcessQueue processQueue, //
    final MessageQueue messageQueue, //
    final long suspendTimeMillis//
) {
    long timeMillis = suspendTimeMillis;
    if (timeMillis == -1) {
        timeMillis = this.defaultMQPushConsumer.getSuspendCurrentQueueTimeMillis();
    }

    if (timeMillis < 10) {
        timeMillis = 10;
    } else if (timeMillis > 30000) {
        timeMillis = 30000;
    }

    this.scheduledExecutorService.schedule(new Runnable() {

        @Override
        public void run() {
            ConsumeMessageOrderlyService.this.submitConsumeRequest(null, processQueue, messageQueue, true);
        }
    }, timeMillis, TimeUnit.MILLISECONDS);
}
 
Example 12
Project: weex-3d-map   File: WXWebSocketManager.java   View source code 6 votes vote down vote up
public void connect(String url) {
  try {
    mHttpClient= (OkHttpClient) Class.forName("com.squareup.okhttp.OkHttpClient").newInstance();
  } catch (Exception e) {
    isSupportWebSocket =false;
    return;
  }
  mHttpClient.setConnectTimeout(10, TimeUnit.SECONDS);
  mHttpClient.setWriteTimeout(10, TimeUnit.SECONDS);
  // Disable timeouts for read
  mHttpClient.setReadTimeout(0, TimeUnit.MINUTES);

  Request request = new Request.Builder().url(url).build();
  WebSocketCall call = WebSocketCall.create(mHttpClient, request);
  call.enqueue(this);
}
 
Example 13
Project: RxJavaEspressoSample   File: RxJava1Activity.java   View source code 6 votes vote down vote up
@Override
protected void onStart() {
    super.onStart();
    compositeSubscription.add(RxView.clicks(binding.buttonDebounce)
            .observeOn(Schedulers.computation())
            .debounce(3, TimeUnit.SECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(v -> binding.textDebounceResult.setText("Debounce Completed")));

    compositeSubscription.add(RxView.clicks(binding.buttonSleep)
            .observeOn(Schedulers.io())
            .map(v -> {
                SystemClock.sleep(3000L);
                return v;
            })
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(v -> binding.textSleepResult.setText("Sleep Completed")));
}
 
Example 14
Project: Go-RxJava   File: RxBinding_Rxlifecycle.java   View source code 6 votes vote down vote up
@Override
public void runCode() {
    super.runCode();
    Observable.interval(2, TimeUnit.SECONDS)
            .compose(this.bindToLifecycle())
            .subscribe(new Action1<Object>() {
                @Override
                public void call(Object num) {
                    println(count++);
                }
            });
    Observable.interval(2, TimeUnit.SECONDS)
            .compose(this.bindUntilEvent(PAUSE))
            .subscribe(new Action1<Object>() {
                @Override
                public void call(Object o) {
                    println(System.currentTimeMillis());
                }
            });
}
 
Example 15
Project: MADBike   File: PlaceAutocompleteAdapter.java   View source code 6 votes vote down vote up
private ArrayList<AutocompletePrediction> getAutocomplete(CharSequence constraint) {
    if (mGoogleApiClient.isConnected()) {

        PendingResult<AutocompletePredictionBuffer> results =
                Places.GeoDataApi
                        .getAutocompletePredictions(mGoogleApiClient, constraint.toString(),
                                mBounds, mPlaceFilter);

        AutocompletePredictionBuffer autocompletePredictions = results
                .await(60, TimeUnit.SECONDS);

        final Status status = autocompletePredictions.getStatus();
        if (!status.isSuccess()) {
            Toast.makeText(getContext(), "Error contacting API: " + status.toString(),
                    Toast.LENGTH_SHORT).show();
            autocompletePredictions.release();
            return null;
        }
        return DataBufferUtils.freezeAndClose(autocompletePredictions);
    }
    return null;
}
 
Example 16
Project: elastic-db-tools-for-java   File: PointMapping.java   View source code 6 votes vote down vote up
/**
 * Performs validation that the local representation is as up-to-date as the representation on the backing data store.
 *
 * @param shardMap
 *            Shard map to which the shard provider belongs.
 * @param conn
 *            Connection used for validation.
 */
@Override
public void validate(StoreShardMap shardMap,
        Connection conn) {
    try {
        log.info("PointMapping Validate Start; Connection: {}", conn.getMetaData().getURL());
        Stopwatch stopwatch = Stopwatch.createStarted();

        ValidationUtils.validateMapping(conn, this.getShardMapManager(), shardMap, this.getStoreMapping());

        stopwatch.stop();

        log.info("PointMapping Validate Complete; Connection: {}; Duration:{}", conn.getMetaData().getURL(),
                stopwatch.elapsed(TimeUnit.MILLISECONDS));
    }
    catch (SQLException e) {
        e.printStackTrace();
        throw (ShardManagementException) e.getCause();
    }
}
 
Example 17
Project: openrouteservice-tools   File: OSMInputFile.java   View source code 6 votes vote down vote up
private Entity getNextPBF()
{
	Entity next = null;
	while (next == null)
	{
		if (!hasIncomingData && _entityQueue.isEmpty())
		{
			// we are done, stop polling
			eof = true;
			break;
		}

		try
		{
			// we cannot use "itemQueue.take()" as it blocks and hasIncomingData can change
			next = _entityQueue.poll(10, TimeUnit.MILLISECONDS);
		} catch (InterruptedException ex)
		{
			eof = true;
			break;
		}
	}

	return next;
}
 
Example 18
Project: fresco_floodlight   File: TopologyManager.java   View source code 6 votes vote down vote up
@Override
public void run() {
	try {
		if (ldUpdates.peek() != null) {
			updateTopology();
		}
		handleMiscellaneousPeriodicEvents();
	}
	catch (Exception e) {
		log.error("Error in topology instance task thread", e);
	} finally {
		if (floodlightProviderService.getRole() != HARole.STANDBY) {
			newInstanceTask.reschedule(TOPOLOGY_COMPUTE_INTERVAL_MS, TimeUnit.MILLISECONDS);
		}
	}
}
 
Example 19
Project: incubator-servicecomb-java-chassis   File: MicroserviceVersions.java   View source code 6 votes vote down vote up
@Subscribe
public void onMicroserviceInstanceChanged(MicroserviceInstanceChangedEvent changedEvent) {
  if (!appId.equals(changedEvent.getKey().getAppId()) ||
      !microserviceName.equals(changedEvent.getKey().getServiceName())) {
    return;
  }

  // pull instances always replace old instances, not append
  //
  // pull result and watch event sequence is not defined even inside SC.
  // it's not safe to trust the event, so we just send a new pull request
  //
  // CREATE/UPDATE:
  //   if pull 1/2/3, and then add 4, but "add 4" received before pull result, will lost 4.
  // DELETE:
  //   if pull 1/2/3, and then delete 3, but "delete 3" received before pull result, will have wrong 3.
  // EXPIRE::
  //   black/white config in SC changed, we must refresh all data from sc.
  pendingPullCount.incrementAndGet();
  appManager.getEventBus().post(new PullMicroserviceVersionsInstancesEvent(this, TimeUnit.SECONDS.toMillis(1)));
}
 
Example 20
Project: illuminati   File: IlluminatiTemplateExecutorImpl.java   View source code 6 votes vote down vote up
@Override public IlluminatiTemplateInterfaceModel deQueueByDebug () {
    ILLUMINATI_TEMPLATE_EXECUTOR_LOGGER.info("template queue current size is "+String.valueOf(this.getQueueSize()));

    if (ILLUMINATI_MODEL_BLOCKING_QUEUE == null || this.getQueueSize() == 0) {
        return null;
    }
    try {
        final long start = System.currentTimeMillis();
        IlluminatiTemplateInterfaceModel illuminatiTemplateInterfaceModel = ILLUMINATI_MODEL_BLOCKING_QUEUE.poll(ILLUMINATI_DEQUEUING_TIMEOUT_MS, TimeUnit.MILLISECONDS);
        final long elapsedTime = System.currentTimeMillis() - start;
        ILLUMINATI_TEMPLATE_EXECUTOR_LOGGER.info("template queue after inserted size is "+String.valueOf(this.getQueueSize()));
        ILLUMINATI_TEMPLATE_EXECUTOR_LOGGER.info("elapsed time of dequeueing template queue is "+elapsedTime+" millisecond");
        return illuminatiTemplateInterfaceModel;
    } catch (InterruptedException e) {
        ILLUMINATI_TEMPLATE_EXECUTOR_LOGGER.warn("Failed to dequeing the rabbitmq queue.. ("+e.getMessage()+")");
    }

    return null;
}
 
Example 21
Project: starcor.xul   File: XulHttpServer.java   View source code 6 votes vote down vote up
private void _initServer(String addr, int port) {
	_localAddr = addr;
	_localPort = port;
	_workerGroup = new ThreadGroup("Xul HTTP Server");
	ThreadFactory threadFactory = new ThreadFactory() {
		@Override
		public Thread newThread(Runnable r) {
			return new Thread(_workerGroup, r, "Reactor");
		}
	};
	_reactorPool = new ThreadPoolExecutor(1, 16, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(16), threadFactory);

	_listeningWorker = new Thread(_workerGroup, "Acceptor") {
		@Override
		public void run() {
			_doWork();
		}
	};
	_listeningWorker.start();
}
 
Example 22
Project: reading-and-annotate-rocketmq-3.4.6   File: FiltersrvController.java   View source code 5 votes vote down vote up
public boolean initialize() {
    MixAll.printObjectProperties(log, this.filtersrvConfig);

    this.remotingServer = new NettyRemotingServer(this.nettyServerConfig);

    this.remotingExecutor =
            Executors.newFixedThreadPool(nettyServerConfig.getServerWorkerThreads(),
                new ThreadFactoryImpl("RemotingExecutorThread_"));

    this.registerProcessor();

    this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {

        @Override
        public void run() {
            FiltersrvController.this.registerFilterServerToBroker();
        }
    }, 3, 10, TimeUnit.SECONDS);

    this.defaultMQPullConsumer.setBrokerSuspendMaxTimeMillis(this.defaultMQPullConsumer
        .getBrokerSuspendMaxTimeMillis() - 1000);
    this.defaultMQPullConsumer.setConsumerTimeoutMillisWhenSuspend(this.defaultMQPullConsumer
        .getConsumerTimeoutMillisWhenSuspend() - 1000);

    this.defaultMQPullConsumer.setNamesrvAddr(this.filtersrvConfig.getNamesrvAddr());
    this.defaultMQPullConsumer.setInstanceName(String.valueOf(UtilAll.getPid()));

    return true;
}
 
Example 23
Project: NBANDROID-V2   File: AndroidSdkImpl.java   View source code 5 votes vote down vote up
@Override
public void setSdkRootFolder(String sdkPath) {
    String last = this.sdkPath;
    this.sdkPath = sdkPath;
    sdkRoot = new File(sdkPath);
    sdkRootFo = FileUtil.toFileObject(sdkRoot);
    firePropertyChange(LOCATION, last, sdkPath);
    platforms.clear();
    platformsList.clear();
    final Runnable runnable = new Runnable() {

        @Override
        public void run() {
            androidSdkHandler = AndroidSdkHandler.getInstance(sdkRoot);
            if (androidSdkHandler != null) {
                repoManager = androidSdkHandler.getSdkManager(new NbOutputWindowProgressIndicator());
                repoManager.registerLocalChangeListener(AndroidSdkImpl.this);
                repoManager.registerRemoteChangeListener(AndroidSdkImpl.this);
                androidTargetManager = androidSdkHandler.getAndroidTargetManager(new NbOutputWindowProgressIndicator() {
                });
                updateSdkPlatformPackages();
                scheduledThreadPool.scheduleWithFixedDelay(new Runnable() {
                    @Override
                    public void run() {
                        repoManager.reloadLocalIfNeeded(new NbOutputWindowProgressIndicator());
                    }
                }, 30, 30, TimeUnit.SECONDS);
            } else {
                repoManager = null;
            }
        }
    };
    WindowManager.getDefault().invokeWhenUIReady(new Runnable() {
        @Override
        public void run() {
            AndroidSdk.pool.submit(runnable);
        }
    });
}
 
Example 24
Project: JRediClients   File: JCacheTest.java   View source code 5 votes vote down vote up
@Test
public void testExpiration() throws InterruptedException, IllegalArgumentException, URISyntaxException, FailedToStartRedisException, IOException {
    RedisProcess runner = new RedisRunner()
            .nosave()
            .randomDir()
            .port(6311)
            .run();

    MutableConfiguration<String, String> config = new MutableConfiguration<>();
    config.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.SECONDS, 1)));
    config.setStoreByValue(true);
    
    URI configUri = getClass().getResource("redisson-jcache.json").toURI();
    Cache<String, String> cache = Caching.getCachingProvider().getCacheManager(configUri, null)
            .createCache("test", config);

    CountDownLatch latch = new CountDownLatch(1);
    
    String key = "123";
    ExpiredListener clientListener = new ExpiredListener(latch, key, "90");
    MutableCacheEntryListenerConfiguration<String, String> listenerConfiguration = 
            new MutableCacheEntryListenerConfiguration<String, String>(FactoryBuilder.factoryOf(clientListener), null, true, true);
    cache.registerCacheEntryListener(listenerConfiguration);

    cache.put(key, "90");
    Assert.assertNotNull(cache.get(key));
    
    latch.await();
    
    Assert.assertNull(cache.get(key));
    
    cache.close();
    runner.stop();
}
 
Example 25
Project: JRediClients   File: RedissonRemoteService.java   View source code 5 votes vote down vote up
private <T extends RRemoteServiceResponse> RFuture<BatchResult<?>> send(long timeout, String responseName, T response) {
    RBatch batch = redisson.createBatch();
    RBlockingQueueAsync<T> queue = batch.getBlockingQueue(responseName, getCodec());
    queue.putAsync(response);
    queue.expireAsync(timeout, TimeUnit.MILLISECONDS);
    return batch.executeAsync();
}
 
Example 26
Project: lemon   File: HttpFuture.java   View source code 5 votes vote down vote up
public String readText(ExecutorService executorService, long timeout)
        throws IOException, InterruptedException, ExecutionException,
        TimeoutException {
    FutureTask<String> futureTask = new FutureTask(this);
    executorService.execute(futureTask);

    String text = futureTask.get(timeout, TimeUnit.MILLISECONDS);

    return text;
}
 
Example 27
Project: hashsdn-controller   File: RpcRegistryTest.java   View source code 5 votes vote down vote up
/**
 * Three node cluster. Register rpc on 2 nodes. Ensure 3rd gets updated.
 */
@Test
public void testRpcAddedOnMultiNodes() throws Exception {
    final JavaTestKit testKit = new JavaTestKit(node3);

    // Add rpc on node 1
    List<DOMRpcIdentifier> addedRouteIds1 = createRouteIds();
    registry1.tell(new AddOrUpdateRoutes(addedRouteIds1), ActorRef.noSender());

    final UpdateRemoteEndpoints req1 = registrar3.expectMsgClass(Duration.create(3, TimeUnit.SECONDS),
        UpdateRemoteEndpoints.class);

    // Add rpc on node 2
    List<DOMRpcIdentifier> addedRouteIds2 = createRouteIds();
    registry2.tell(new AddOrUpdateRoutes(addedRouteIds2), ActorRef.noSender());

    final UpdateRemoteEndpoints req2 = registrar3.expectMsgClass(Duration.create(3, TimeUnit.SECONDS),
        UpdateRemoteEndpoints.class);
    Address node2Address = node2.provider().getDefaultAddress();
    Address node1Address = node1.provider().getDefaultAddress();

    Map<Address, Bucket<RoutingTable>> buckets = retrieveBuckets(registry3, testKit, node1Address,
            node2Address);

    verifyBucket(buckets.get(node1Address), addedRouteIds1);
    verifyBucket(buckets.get(node2Address), addedRouteIds2);

    Map<Address, Long> versions = retrieveVersions(registry3, testKit);
    Assert.assertEquals("Version for bucket " + node1Address, (Long) buckets.get(node1Address).getVersion(),
            versions.get(node1Address));
    Assert.assertEquals("Version for bucket " + node2Address, (Long) buckets.get(node2Address).getVersion(),
            versions.get(node2Address));

    assertEndpoints(req1, node1Address, invoker1);
    assertEndpoints(req2, node2Address, invoker2);

}
 
Example 28
Project: AthenaX   File: InstanceManager.java   View source code 5 votes vote down vote up
@Override
public void run() {
  try {
    scanAll();
  } catch (Throwable e) {
    LOG.warn("Failed to scan the applications {}", e);
  } finally {
    if (running) {
      executor.schedule(thunk, rescanInterval, TimeUnit.MILLISECONDS);
    }
  }
}
 
Example 29
Project: Equella   File: ResourcesServlet.java   View source code 5 votes vote down vote up
public ResourcesServlet()
{
	long twentyFiveYearsInMillis = TimeUnit.DAYS.toMillis(365) * 25;

	maxAge = "max-age=" + TimeUnit.MILLISECONDS.toSeconds(twentyFiveYearsInMillis) + ", public";
	expires = System.currentTimeMillis() + twentyFiveYearsInMillis;
}
 
Example 30
Project: HuskyCrates-Sponge   File: InstantGUIView.java   View source code 5 votes vote down vote up
public InstantGUIView(HuskyCrates plugin, Player runner, VirtualCrate virtualCrate){
    //System.out.println("AA");
    this.plugin = plugin;
    vc = virtualCrate;
    ourplr = runner;
    items = vc.getItemSet();
    if(virtualCrate.scrambleRewards){
        scrambleRewards();
    }
    disp = Inventory.builder()
            .of(InventoryArchetypes.DISPENSER)
            .listener(InteractInventoryEvent.class, evt ->{
                if(!(evt instanceof InteractInventoryEvent.Open) && !(evt instanceof  InteractInventoryEvent.Close)){
                    evt.setCancelled(true);
                }

            })
            .property(InventoryTitle.PROPERTY_NAME,InventoryTitle.of(TextSerializers.FORMATTING_CODE.deserialize(virtualCrate.displayName)))
            .build(plugin);
    updateInv(0);
    Scheduler scheduler = Sponge.getScheduler();
    Task.Builder taskBuilder = scheduler.createTaskBuilder();
    updater = taskBuilder.execute(this::updateTick).intervalTicks(1).submit(plugin);
    scheduler.createTaskBuilder().execute(() -> {
        updater.cancel();
        ourplr.closeInventory();
        handleReward(holder);
        ourplr.playSound(SoundTypes.ENTITY_EXPERIENCE_ORB_PICKUP,ourplr.getLocation().getPosition(),1);
    }).delay(3, TimeUnit.SECONDS).submit(HuskyCrates.instance);
}
 
Example 31
Project: jdk8u-jdk   File: bug6489130.java   View source code 5 votes vote down vote up
public static void main(String[] args) throws InterruptedException {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            new bug6489130().run();
        }
    });

    if (!MUX.await(10, TimeUnit.SECONDS)) {
        throw new RuntimeException("Timeout");
    }
}
 
Example 32
Project: LoRaWAN-Smart-Parking   File: OkHttpClient.java   View source code 5 votes vote down vote up
/**
 * Sets the default connect timeout for new connections. A value of 0 means no timeout.
 *
 * @see URLConnection#setConnectTimeout(int)
 */
public void setConnectTimeout(long timeout, TimeUnit unit) {
  if (timeout < 0) {
    throw new IllegalArgumentException("timeout < 0");
  }
  if (unit == null) {
    throw new IllegalArgumentException("unit == null");
  }
  long millis = unit.toMillis(timeout);
  if (millis > Integer.MAX_VALUE) {
    throw new IllegalArgumentException("Timeout too large.");
  }
  connectTimeout = (int) millis;
}
 
Example 33
Project: otter-G   File: MonitorScheduler.java   View source code 5 votes vote down vote up
/**
 * 注册对应的Monitor对象
 * 
 * @param monitor
 * @param period 调度周期,单位ms
 */
public static void register(final Monitor monitor, Long delay, Long period) {
    ScheduledFuture future = scheduler.scheduleAtFixedRate(new Runnable() {

        public void run() {
            monitor.reload();
        }
    }, delay, period, TimeUnit.MILLISECONDS);

    register.put(monitor, future);
}
 
Example 34
Project: GitHub   File: SimpleMockService.java   View source code 5 votes vote down vote up
public static void main(String... args) throws IOException {
  // Create a very simple Retrofit adapter which points the GitHub API.
  Retrofit retrofit = new Retrofit.Builder()
      .baseUrl(SimpleService.API_URL)
      .build();

  // Create a MockRetrofit object with a NetworkBehavior which manages the fake behavior of calls.
  NetworkBehavior behavior = NetworkBehavior.create();
  MockRetrofit mockRetrofit = new MockRetrofit.Builder(retrofit)
      .networkBehavior(behavior)
      .build();

  BehaviorDelegate<GitHub> delegate = mockRetrofit.create(GitHub.class);
  MockGitHub gitHub = new MockGitHub(delegate);

  // Query for some contributors for a few repositories.
  printContributors(gitHub, "square", "retrofit");
  printContributors(gitHub, "square", "picasso");

  // Using the mock-only methods, add some additional data.
  System.out.println("Adding more mock data...\n");
  gitHub.addContributor("square", "retrofit", "Foo Bar", 61);
  gitHub.addContributor("square", "picasso", "Kit Kat", 53);

  // Reduce the delay to make the next calls complete faster.
  behavior.setDelay(500, TimeUnit.MILLISECONDS);

  // Query for the contributors again so we can see the mock data that was added.
  printContributors(gitHub, "square", "retrofit");
  printContributors(gitHub, "square", "picasso");
}
 
Example 35
Project: GitHub   File: HandlerSchedulerTest.java   View source code 5 votes vote down vote up
@Test
public void directScheduleOnceWithNegativeDelayPostsImmediately() {
    CountingRunnable counter = new CountingRunnable();
    scheduler.scheduleDirect(counter, -1, TimeUnit.MINUTES);

    runUiThreadTasks();
    assertEquals(1, counter.get());
}
 
Example 36
Project: Channelize   File: TimerFragment.java   View source code 5 votes vote down vote up
private void setScreenElements() {
    mCircularProgressBar = (HoloCircularProgressBar) view.findViewById(R.id.circular_progressBar);
    mTextViewTimer = (TextView)view.findViewById(R.id.text_timer);
    mButtonStart = (Button)view.findViewById(R.id.button_start);
    mButtonPause = (Button)view.findViewById(R.id.button_pause);
    mButtonResume = (Button)view.findViewById(R.id.button_resume);
    mButtonStop = (Button)view.findViewById(R.id.button_stop);

    if (mTextViewTimer != null) {
        mTextViewTimer.setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/Roboto-Light.ttf"));
    }

    updateTimerLabel((int) TimeUnit.MINUTES.toSeconds(timerDuration));
}
 
Example 37
Project: letv   File: LooperScheduler.java   View source code 5 votes vote down vote up
public Subscription schedule(Action0 action, long delayTime, TimeUnit unit) {
    if (this.unsubscribed) {
        return Subscriptions.unsubscribed();
    }
    Subscription scheduledAction = new ScheduledAction(this.hook.onSchedule(action), this.handler);
    Message message = Message.obtain(this.handler, scheduledAction);
    message.obj = this;
    this.handler.sendMessageDelayed(message, unit.toMillis(delayTime));
    if (!this.unsubscribed) {
        return scheduledAction;
    }
    this.handler.removeCallbacks(scheduledAction);
    return Subscriptions.unsubscribed();
}
 
Example 38
Project: L2J-Global   File: ThreadPoolManager.java   View source code 5 votes vote down vote up
/**
 * Schedules a general task to be executed at fixed rate.
 * @param task the task to execute
 * @param initialDelay the initial delay in the given time unit
 * @param period the period between executions in the given time unit
 * @param unit the time unit of the initialDelay and period parameters
 * @return a ScheduledFuture representing pending completion of the task, and whose get() method will throw an exception upon cancellation
 */
public ScheduledFuture<?> scheduleGeneralAtFixedRate(Runnable task, long initialDelay, long period, TimeUnit unit)
{
	try
	{
		return _generalScheduledThreadPool.scheduleAtFixedRate(new RunnableWrapper(task), initialDelay, period, unit);
	}
	catch (RejectedExecutionException e)
	{
		return null; /* shutdown, ignore */
	}
}
 
Example 39
Project: OpenJSharp   File: FileTime.java   View source code 5 votes vote down vote up
private long toDays() {
    if (unit != null) {
        return unit.toDays(value);
    } else {
        return TimeUnit.SECONDS.toDays(toInstant().getEpochSecond());
    }
}
 
Example 40
Project: hadoop   File: FairCallQueue.java   View source code 5 votes vote down vote up
@Override
public boolean offer(E e, long timeout, TimeUnit unit)
    throws InterruptedException {
  int priorityLevel = scheduler.getPriorityLevel(e);
  BlockingQueue<E> q = this.queues.get(priorityLevel);
  boolean ret = q.offer(e, timeout, unit);

  signalNotEmpty();

  return ret;
}