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: auto-scale-java   File: OKHttpUtil.java   Source Code and License 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 2
Project: MADBike   File: PlaceAutocompleteAdapter.java   Source Code and License 7 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 3
Project: ditb   File: TestIdLock.java   Source Code and License 7 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 4
Project: orange-mathoms-logging   File: ThreadPoolTaskExecutorWithMdcPropagationTest.java   Source Code and License 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 5
Project: config   File: SimpleConfigPropertyTest.java   Source Code and License 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 6
Project: lams   File: SimpleNonceManager.java   Source Code and License 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 7
Project: Dalaran   File: XApiServiceHelper.java   Source Code and License 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 8
Project: drinkwater-java   File: Main.java   Source Code and License 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 9
Project: GitHub   File: CacheTest.java   Source Code and License 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 10
Project: iTAP-controller   File: SwitchResourceBase.java   Source Code and License 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 11
Project: neoscada   File: Activator.java   Source Code and License 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 12
Project: rocketmq-rocketmq-all-4.1.0-incubating   File: ConsumeMessageOrderlyService.java   Source Code and License 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 13
Project: weex-3d-map   File: WXWebSocketManager.java   Source Code and License 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 14
Project: RxJavaEspressoSample   File: RxJava1Activity.java   Source Code and License 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 15
Project: Go-RxJava   File: RxBinding_Rxlifecycle.java   Source Code and License 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 16
Project: elastic-db-tools-for-java   File: PointMapping.java   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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;
}
 
Example 41
Project: flume-release-1.7.0   File: ThriftTestingSource.java   Source Code and License 5 votes vote down vote up
@Override
public Status append(ThriftFlumeEvent event) throws TException {
  try {
    TimeUnit.MILLISECONDS.sleep(1550);
  } catch (InterruptedException e) {
    throw new FlumeException("Error", e);
  }
  return super.append(event);
}
 
Example 42
Project: IPCInvoker   File: InvokeFuture.java   Source Code and License 5 votes vote down vote up
@Override
public T get(long timeout, @NonNull TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
    if (!hasResult) {
        synchronized (lock) {
            if (!hasResult) {
                lock.wait(unit.toMillis(timeout));
            }
        }
    }
    return result;
}
 
Example 43
Project: neoscada   File: ChartViewer.java   Source Code and License 5 votes vote down vote up
public void pageTimespan ( final long duration, final TimeUnit timeUnit )
{
    processX ( new AxisFunction<org.eclipse.scada.chart.XAxis> () {

        @Override
        public void process ( final org.eclipse.scada.chart.XAxis axis )
        {
            axis.shiftByTimespan ( duration, timeUnit );
        }
    } );
}
 
Example 44
Project: GabrielBot   File: InteractiveOperations.java   Source Code and License 5 votes vote down vote up
public static Future<Void> createOrGet(long channelId, long timeoutSeconds, InteractiveOperation operation) {
    if(timeoutSeconds < 1) throw new IllegalArgumentException("Timeout < 1");
    if(operation == null) throw new NullPointerException("operation");
    RunningOperation o = OPERATIONS.get(channelId);
    if(o != null) return o.future;
    o = new RunningOperation(operation, new OperationFuture(channelId));
    OPERATIONS.put(channelId, o, timeoutSeconds, TimeUnit.SECONDS);
    return o.future;
}
 
Example 45
Project: RxJava3-preview   File: ObservableWindowWithTimeTest.java   Source Code and License 5 votes vote down vote up
@Test
public void timespanDefaultSchedulerSizeRestart() {
    Observable.range(1, 10)
    .window(1, TimeUnit.MINUTES, 20, true)
    .flatMap(Functions.<Observable<Integer>>identity(), true)
    .test()
    .awaitDone(5, TimeUnit.SECONDS)
    .assertResult(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
}
 
Example 46
Project: RxCommand   File: RxCommandTest.java   Source Code and License 5 votes vote down vote up
@Test
public void executionObservables_allowingConcurrent_executionMultiTimes() {
    RxCommand<String> command = RxCommand.create(o -> Observable.just((String) o)
            .subscribeOn(Schedulers.newThread())
            .delay(10, TimeUnit.MILLISECONDS)
    );

    // allows concurrent
    command.setAllowsConcurrentExecution(true);

    TestObserver<Observable<String>> testObserver = new TestObserver<>();
    TestObserver<String> stringTestObserver = new TestObserver<>();

    command.executionObservables()
            .subscribe(testObserver);

    command.executionObservables()
            .flatMap(stringObservable -> stringObservable)
            .subscribe(stringTestObserver);

    command.execute("1");
    command.execute("2");
    command.execute("3");

    // wait
    try {
        Thread.sleep(30);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    testObserver.assertValueCount(3);
    testObserver.assertNoErrors();
    testObserver.assertNotComplete();

    stringTestObserver.assertValueCount(3);
    stringTestObserver.assertValueSet(Arrays.asList("1", "2", "3"));
}
 
Example 47
Project: hadoop   File: TestMultiThreadedHflush.java   Source Code and License 5 votes vote down vote up
private void doAWrite() throws IOException {
  StopWatch sw = new StopWatch().start();
  stm.write(toWrite);
  stm.hflush();
  long micros = sw.now(TimeUnit.MICROSECONDS);
  quantiles.insert(micros);
}
 
Example 48
Project: otus_java_2017_06   File: ServerMain.java   Source Code and License 5 votes vote down vote up
private void startClient(ScheduledExecutorService executorService) {
    executorService.schedule(() -> {
        try {
            new ProcessRunnerImpl().start(CLIENT_START_COMMAND);
        } catch (IOException e) {
            logger.log(Level.SEVERE, e.getMessage());
        }
    }, CLIENT_START_DELAY_SEC, TimeUnit.SECONDS);
}
 
Example 49
Project: GitHub   File: JobScheduler.java   Source Code and License 5 votes vote down vote up
private void enqueueJob(long delay) {
  // If we make mExecutor be a {@link ScheduledexecutorService}, we could just have
  // `mExecutor.schedule(mDoJobRunnable, delay)` and avoid mSubmitJobRunnable and
  // JobStartExecutorSupplier altogether. That would require some refactoring though.
  if (delay > 0) {
    JobStartExecutorSupplier.get().schedule(mSubmitJobRunnable, delay, TimeUnit.MILLISECONDS);
  } else {
    mSubmitJobRunnable.run();
  }
}
 
Example 50
Project: lazycat   File: WsServerContainer.java   Source Code and License 5 votes vote down vote up
private void shutdownExecutor() {
	if (executorService == null) {
		return;
	}
	executorService.shutdown();
	try {
		executorService.awaitTermination(10, TimeUnit.SECONDS);
	} catch (InterruptedException e) {
		// Ignore the interruption and carry on
	}
}
 
Example 51
Project: lazycat   File: StandardThreadExecutor.java   Source Code and License 5 votes vote down vote up
@Override
public void execute(Runnable command, long timeout, TimeUnit unit) {
	if (executor != null) {
		executor.execute(command, timeout, unit);
	} else {
		throw new IllegalStateException("StandardThreadExecutor not started.");
	}
}
 
Example 52
Project: swage   File: StateCaptureTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testScheduledExecutorServiceCaptures() throws InterruptedException {
    // Setup
    ScheduledExecutorService e = Executors.newScheduledThreadPool(10);
    ScheduledExecutorService f = StateCapture.capturingDecorator(e);

    CapturedState mockCapturedState = mock(CapturedState.class);
    Runnable mockRunnable = mock(Runnable.class);
    ThreadLocalStateCaptor.THREAD_LOCAL.set(mockCapturedState);
    f.execute(mockRunnable);
    e.shutdown();
    e.awaitTermination(10, TimeUnit.HOURS);

    verifyStandardCaptures(mockCapturedState, mockRunnable);
}
 
Example 53
Project: GitHub   File: ApiTestActivity.java   Source Code and License 4 votes vote down vote up
public void setMaxStaleCacheControl(View view) {
    AndroidNetworking.get(ApiEndPoint.BASE_URL + ApiEndPoint.GET_JSON_ARRAY)
            .addPathParameter("pageNumber", "0")
            .addQueryParameter("limit", "3")
            .setTag(this)
            .setPriority(Priority.LOW)
            .setMaxStaleCacheControl(365, TimeUnit.SECONDS)
            .build()
            .setAnalyticsListener(new AnalyticsListener() {
                @Override
                public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) {
                    Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis);
                    Log.d(TAG, " bytesSent : " + bytesSent);
                    Log.d(TAG, " bytesReceived : " + bytesReceived);
                    Log.d(TAG, " isFromCache : " + isFromCache);
                }
            })
            .getAsJSONArray(new JSONArrayRequestListener() {
                @Override
                public void onResponse(JSONArray response) {
                    Log.d(TAG, "onResponse array : " + response.toString());
                    Log.d(TAG, "onResponse isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper()));
                }

                @Override
                public void onError(ANError error) {
                    if (error.getErrorCode() != 0) {
                        // received ANError from server
                        // error.getErrorCode() - the ANError code from server
                        // error.getErrorBody() - the ANError body from server
                        // error.getErrorDetail() - just a ANError detail
                        Log.d(TAG, "onError errorCode : " + error.getErrorCode());
                        Log.d(TAG, "onError errorBody : " + error.getErrorBody());
                        Log.d(TAG, "onError errorDetail : " + error.getErrorDetail());
                    } else {
                        // error.getErrorDetail() : connectionError, parseError, requestCancelledError
                        Log.d(TAG, "onError errorDetail : " + error.getErrorDetail());
                    }
                }
            });
}
 
Example 54
Project: tcp-gateway   File: NotifyFuture.java   Source Code and License 4 votes vote down vote up
public V get() throws InterruptedException {
    return get(timeout, TimeUnit.MILLISECONDS);
}
 
Example 55
Project: hashsdn-controller   File: ForwardingDOMNotificationPublishService.java   Source Code and License 4 votes vote down vote up
@Override
public ListenableFuture<?> offerNotification(final DOMNotification notification, final long timeout,
        final TimeUnit unit) throws InterruptedException {
    return delegate().offerNotification(notification, timeout, unit);
}
 
Example 56
Project: OperatieBRP   File: MaakSelectieResultaatTaakVerwerkerServiceImpl.java   Source Code and License 4 votes vote down vote up
private void wachtTotProducerKlaar(Future<Object> producerFuture)
        throws InterruptedException, ExecutionException, TimeoutException {
    final long wachttijd = configuratieService.getMaximaleWachttijdFragmentVerwerkerMin();
    producerFuture.get(wachttijd, TimeUnit.MINUTES);
}
 
Example 57
Project: JukeBot   File: Helpers.java   Source Code and License 4 votes vote down vote up
public static void schedule(Consumer<Runnable> task, int delay, TimeUnit unit) {
    timer.schedule(() -> task.accept(null), delay, unit);
}
 
Example 58
Project: sstore-soft   File: TestCommandLoggerSuite.java   Source Code and License 4 votes vote down vote up
/**
 * testConcurrentTxns
 */
public void testConcurrentTxns() throws Exception {
    Client client = this.getClient();
    this.initializeDatabase(client);
    
    final int num_txns = 500;
    final CountDownLatch latch = new CountDownLatch(num_txns);
    final AtomicInteger numTotal = new AtomicInteger(0);
    final AtomicInteger numCompleted = new AtomicInteger(0);
    final AtomicInteger numFailed = new AtomicInteger(0);
    
    ProcedureCallback callback = new ProcedureCallback() {
        @Override
        public void clientCallback(ClientResponse cr) {
            switch (cr.getStatus()) {
                case OK:
                    if (cr.getResults()[0].asScalarLong() == VoterConstants.VOTE_SUCCESSFUL) { 
                        numCompleted.incrementAndGet();
                    }
                    break;
                default:
                    numFailed.incrementAndGet();
                    System.err.printf("UNEXPECTED: %s [%d]\n", cr.getStatus(), numFailed.get());
            } // SWITCH
            numTotal.incrementAndGet();
            latch.countDown();
        }
    };
    
    for (int i = 0; i < num_txns; i++) {
        Object params[] = {
            new Long(i),
            PHONE_NUMBER + (i % 10),
            i % VoterConstants.NUM_CONTESTANTS,
            MAX_VOTES_PER_PHONE_NUMBER
        };
        client.callProcedure(callback, Vote.class.getSimpleName(), params);
    } // FOR
    System.err.printf("Invoked %d txns. Waiting for responses...\n", num_txns);
    boolean result = latch.await(15, TimeUnit.SECONDS);
    System.err.println("LATCH RESULT: " + result);
    System.err.println("TOTAL:        " + numTotal.get() + " / " + num_txns);
    System.err.println("COMPLETED:    " + numCompleted.get());
    System.err.println("FAILED:       " + numFailed.get());
    if (result == false) {
        System.err.println("BAD MOJO");
    }
    
    assertTrue("Timed out [latch="+latch.getCount() + "]", result);
    assertEquals(0, numFailed.get());
    
    // At this point we know that all of our txns have been committed to disk
    // Make sure that our vote is actually in the real table and materialized views
    String query = "SELECT COUNT(*) FROM votes";
    ClientResponse cresponse = client.callProcedure("@AdHoc", query);
    System.err.println(cresponse);
    assertEquals(Status.OK, cresponse.getStatus());
    VoltTable results[] = cresponse.getResults();
    assertEquals(1, results.length);
    assertEquals(numCompleted.get(), results[0].asScalarLong());
    
    
    // TODO: We should go through the log and make sure that all of our
    // transactions are still in there...
}
 
Example 59
Project: canal_mysql_elasticsearch_sync   File: SyncServiceImpl.java   Source Code and License 4 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
    cachedThreadPool = new ThreadPoolExecutor(5, 5, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(), (ThreadFactory) Thread::new);
}
 
Example 60
Project: garras   File: NewFragment.java   Source Code and License 4 votes vote down vote up
@Override
public void bindEvenListener(@Nullable Bundle savedInstanceState) {
    super.bindEvenListener(savedInstanceState);
    allowSwipeBack(false);
    unbinder = ButterKnife.bind(this, viewDelegate.getRootView());
    if (null == getActivity()) return;
    mLocalBroadcastManager = LocalBroadcastManager.getInstance(getActivity());
    mRefreshBroadcastReceiver = new RefreshBroadcastReceiver();
    mLocalBroadcastManager.registerReceiver(mRefreshBroadcastReceiver, new IntentFilter("refresh"));

    mDataManager = new DataManager();
    mSwipeRefreshLayout.setOnRefreshListener(this);
    mDatas = new ArrayList<>();

    final GlideRequests glideRequests = GlideApp.with(PixelsApplication.getInstance());
    GlideRequest<Drawable> fullRequest = glideRequests
            .asDrawable()
            .centerCrop()
            .placeholder(new ColorDrawable(Color.GRAY));

    GlideRequest<Drawable> thumbRequest = glideRequests
            .asDrawable()
            .diskCacheStrategy(DiskCacheStrategy.DATA)
            .transition(withCrossFade());

    mAdapter = new PhotoAdapter(fullRequest, thumbRequest);
    mAdapter.setOnLoadMoreListener(this, mRecyclerView);
    mLayoutManager = new LinearLayoutManager(getActivity());
    mRecyclerView.setLayoutManager(mLayoutManager);
    mRecyclerView.setItemViewCacheSize(10);
    mRecyclerView.setDrawingCacheEnabled(true);
    mRecyclerView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
    mRecyclerView.setAdapter(mAdapter);

    ViewPreloadSizeProvider<Photos> preloadSizeProvider = new ViewPreloadSizeProvider<>();
    RecyclerViewPreloader<Photos> preloader =
            new RecyclerViewPreloader<>(
                    GlideApp.with(this), mAdapter, preloadSizeProvider, PRELOAD_AHEAD_ITEMS);

    mRecyclerView.addOnScrollListener(preloader);
    mRecyclerView.setItemViewCacheSize(0);

    mRecyclerView.setRecyclerListener(new RecyclerView.RecyclerListener() {
        @Override
        public void onViewRecycled(RecyclerView.ViewHolder holder) {
            BaseViewHolder holder1 = (BaseViewHolder) holder;
            AppCompatImageView imageView = holder1.getView(R.id.item_image);
            if (null != imageView) {
                glideRequests.clear(imageView);
            }
        }
    });
    RxView.clicks(mRetryBtn).compose(this.bindUntilEvent(FragmentEvent.DESTROY_VIEW)).throttleFirst(1, TimeUnit.SECONDS).subscribe(new Consumer<Object>() {
        @Override
        public void accept(Object o) throws Exception {
            mSwipeRefreshLayout.setVisibility(View.VISIBLE);
            mStateView.setVisibility(View.GONE);
            startRefresh();
        }
    });
    if (null != savedInstanceState) {
        int index = savedInstanceState.getInt(STATE_POSITION_INDEX);
        int offset = savedInstanceState.getInt(STATE_POSITION_OFFSET);
        mLayoutManager.scrollToPositionWithOffset(index, offset);
    }
}