Java Code Examples for java.util.concurrent.TimeUnit#SECONDS

The following examples show how to use java.util.concurrent.TimeUnit#SECONDS . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RestTemplateConfig.java    From WeBASE-Front with Apache License 2.0 6 votes vote down vote up
/**
 * httpRequestFactory.
 * 
 * @return
 */
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {

    PoolingHttpClientConnectionManager pollingConnectionManager = new PoolingHttpClientConnectionManager(
            30, TimeUnit.SECONDS);
    // max connection
    pollingConnectionManager.setMaxTotal(constants.getRestTemplateMaxTotal());

    pollingConnectionManager.setDefaultMaxPerRoute(constants.getRestTemplateMaxPerRoute());
    HttpClientBuilder httpClientBuilder = HttpClients.custom();
    httpClientBuilder.setConnectionManager(pollingConnectionManager);
    // add Keep-Alive
    httpClientBuilder
            .setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy());
    HttpClient httpClient = httpClientBuilder.build();
    HttpComponentsClientHttpRequestFactory clientHttpRequestFactory =
            new HttpComponentsClientHttpRequestFactory(httpClient);
    clientHttpRequestFactory.setReadTimeout(constants.getHttp_read_timeOut());
    clientHttpRequestFactory.setConnectTimeout(constants.getHttp_connect_timeOut());
    return clientHttpRequestFactory;
}
 
Example 2
Source File: HttpDownloadManager.java    From AppUpdate with Apache License 2.0 6 votes vote down vote up
@Override
public void download(String apkUrl, String apkName, OnDownloadListener listener) {
    this.apkUrl = apkUrl;
    this.apkName = apkName;
    this.listener = listener;
    ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>(), new ThreadFactory() {
        @Override
        public Thread newThread(@NonNull Runnable r) {
            Thread thread = new Thread(r);
            thread.setName(Constant.THREAD_NAME);
            return thread;
        }
    });
    executor.execute(runnable);
}
 
Example 3
Source File: LogRollBackupSubprocedurePool.java    From hbase with Apache License 2.0 5 votes vote down vote up
public LogRollBackupSubprocedurePool(String name, Configuration conf) {
  // configure the executor service
  long keepAlive =
      conf.getLong(LogRollRegionServerProcedureManager.BACKUP_TIMEOUT_MILLIS_KEY,
        LogRollRegionServerProcedureManager.BACKUP_TIMEOUT_MILLIS_DEFAULT);
  int threads = conf.getInt(CONCURENT_BACKUP_TASKS_KEY, DEFAULT_CONCURRENT_BACKUP_TASKS);
  this.name = name;
  executor =
      new ThreadPoolExecutor(1, threads, keepAlive, TimeUnit.SECONDS,
          new LinkedBlockingQueue<>(),
          Threads.newDaemonThreadFactory("rs(" + name + ")-backup"));
  taskPool = new ExecutorCompletionService<>(executor);
}
 
Example 4
Source File: AsynchronousSectionedRenderer.java    From vespa with Apache License 2.0 5 votes vote down vote up
private static ThreadPoolExecutor createExecutor() {
    int threadCount = Runtime.getRuntime().availableProcessors();
    ThreadPoolExecutor executor = new ThreadPoolExecutor(threadCount, threadCount, 1L, TimeUnit.SECONDS,
                                                         new LinkedBlockingQueue<>(),
                                                         ThreadFactoryFactory.getThreadFactory("rendering"));
    executor.prestartAllCoreThreads();
    return executor;
}
 
Example 5
Source File: HBaseAutoConfiguration.java    From dew with Apache License 2.0 5 votes vote down vote up
/**
 * Init HBase connection.
 *
 * @param hbaseProperties hbase settings properties
 * @return HBase connection
 * @throws IOException IOException
 */
@Bean
public Connection connection(HBaseProperties hbaseProperties, org.apache.hadoop.conf.Configuration conf) throws IOException {
    if ("kerberos".equalsIgnoreCase(hbaseProperties.getAuth().getType())) {
        System.setProperty("java.security.krb5.conf", hbaseProperties.getAuth().getKrb5());
        UserGroupInformation.setConfiguration(conf);
        UserGroupInformation.loginUserFromKeytab(hbaseProperties.getAuth().getPrincipal(), hbaseProperties.getAuth().getKeytab());
    }
    ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(200, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<>());
    poolExecutor.prestartCoreThread();
    return ConnectionFactory.createConnection(conf, poolExecutor);
}
 
Example 6
Source File: AndroidExecutors.java    From Bolts-Android with MIT License 5 votes vote down vote up
/**
 * Creates a proper Cached Thread Pool. Tasks will reuse cached threads if available
 * or create new threads until the core pool is full. tasks will then be queued. If an
 * task cannot be queued, a new thread will be created unless this would exceed max pool
 * size, then the task will be rejected. Threads will time out after 1 second.
 *
 * Core thread timeout is only available on android-9+.
 *
 * @param threadFactory the factory to use when creating new threads
 * @return the newly created thread pool
 */
public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
  ThreadPoolExecutor executor =  new ThreadPoolExecutor(
          CORE_POOL_SIZE,
          MAX_POOL_SIZE,
          KEEP_ALIVE_TIME, TimeUnit.SECONDS,
          new LinkedBlockingQueue<Runnable>(),
          threadFactory);

  allowCoreThreadTimeout(executor, true);

  return executor;
}
 
Example 7
Source File: BatchHelper.java    From hadoop-connectors with Apache License 2.0 5 votes vote down vote up
private static ExecutorService newRequestsExecutor(int numThreads) {
  ThreadPoolExecutor requestsExecutor =
      new ThreadPoolExecutor(
          /* corePoolSize= */ numThreads,
          /* maximumPoolSize= */ numThreads,
          /* keepAliveTime= */ 5, TimeUnit.SECONDS,
          new LinkedBlockingQueue<>(numThreads * 20),
          THREAD_FACTORY);
  // Prevents memory leaks in case flush() method was not called.
  requestsExecutor.allowCoreThreadTimeOut(true);
  requestsExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
  return requestsExecutor;
}
 
Example 8
Source File: ObsService.java    From huaweicloud-sdk-java-obs with Apache License 2.0 5 votes vote down vote up
protected ThreadPoolExecutor initThreadPool(AbstractBulkRequest request) {
    int taskThreadNum = request.getTaskThreadNum();
    int workQueenLength = request.getTaskQueueNum();
    ThreadPoolExecutor executor = new ThreadPoolExecutor(taskThreadNum, taskThreadNum, 0, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>(workQueenLength));
    executor.setRejectedExecutionHandler(new BlockRejectedExecutionHandler());
    return executor;
}
 
Example 9
Source File: HttpSolrCall.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
protected void autoCreateSystemColl(String corename) throws Exception {
  if (core == null &&
      SYSTEM_COLL.equals(corename) &&
      "POST".equals(req.getMethod()) &&
      !cores.getZkController().getClusterState().hasCollection(SYSTEM_COLL)) {
    log.info("Going to auto-create {} collection", SYSTEM_COLL);
    SolrQueryResponse rsp = new SolrQueryResponse();
    String repFactor = String.valueOf(Math.min(3, cores.getZkController().getClusterState().getLiveNodes().size()));
    cores.getCollectionsHandler().handleRequestBody(new LocalSolrQueryRequest(null,
        new ModifiableSolrParams()
            .add(ACTION, CREATE.toString())
            .add( NAME, SYSTEM_COLL)
            .add(REPLICATION_FACTOR, repFactor)), rsp);
    if (rsp.getValues().get("success") == null) {
      throw new SolrException(ErrorCode.SERVER_ERROR, "Could not auto-create " + SYSTEM_COLL + " collection: "+ Utils.toJSONString(rsp.getValues()));
    }
    TimeOut timeOut = new TimeOut(3, TimeUnit.SECONDS, TimeSource.NANO_TIME);
    for (; ; ) {
      if (cores.getZkController().getClusterState().getCollectionOrNull(SYSTEM_COLL) != null) {
        break;
      } else {
        if (timeOut.hasTimedOut()) {
          throw new SolrException(ErrorCode.SERVER_ERROR, "Could not find " + SYSTEM_COLL + " collection even after 3 seconds");
        }
        timeOut.sleep(50);
      }
    }

    action = RETRY;
  }
}
 
Example 10
Source File: TestHBaseFsckMOB.java    From hbase with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setUpBeforeClass() throws Exception {
  TEST_UTIL.getConfiguration().set(CoprocessorHost.MASTER_COPROCESSOR_CONF_KEY,
      MasterSyncCoprocessor.class.getName());

  conf.setInt("hbase.regionserver.handler.count", 2);
  conf.setInt("hbase.regionserver.metahandler.count", 30);

  conf.setInt("hbase.htable.threads.max", POOL_SIZE);
  conf.setInt("hbase.hconnection.threads.max", 2 * POOL_SIZE);
  conf.setInt("hbase.hbck.close.timeout", 2 * REGION_ONLINE_TIMEOUT);
  conf.setInt(HConstants.HBASE_RPC_TIMEOUT_KEY, 8 * REGION_ONLINE_TIMEOUT);
  TEST_UTIL.startMiniCluster(1);

  tableExecutorService = new ThreadPoolExecutor(1, POOL_SIZE, 60, TimeUnit.SECONDS,
      new SynchronousQueue<>(), Threads.newDaemonThreadFactory("testhbck"));

  hbfsckExecutorService = new ScheduledThreadPoolExecutor(POOL_SIZE);

  AssignmentManager assignmentManager =
      TEST_UTIL.getHBaseCluster().getMaster().getAssignmentManager();
  regionStates = assignmentManager.getRegionStates();

  connection = TEST_UTIL.getConnection();

  admin = connection.getAdmin();
  admin.balancerSwitch(false, true);

  TEST_UTIL.waitUntilAllRegionsAssigned(TableName.META_TABLE_NAME);
}
 
Example 11
Source File: JBossLoggingReporter.java    From hawkular-agent with Apache License 2.0 5 votes vote down vote up
private Builder(MetricRegistry registry) {
    this.registry = registry;
    this.logger = Logger.getLogger(JBossLoggingReporter.class);
    this.rateUnit = TimeUnit.SECONDS;
    this.durationUnit = TimeUnit.MILLISECONDS;
    this.filter = MetricFilter.ALL;
    this.loggingLevel = LoggingLevel.INFO;
}
 
Example 12
Source File: LDNetDiagnoService.java    From AndroidHttpCapture with MIT License 5 votes vote down vote up
/**
 * 初始化网络诊断服务
 *
 * @param theAppCode
 * @param theDeviceID
 * @param theUID
 * @param theDormain
 */
public LDNetDiagnoService(Context context, String theAppCode,
    String theAppName, String theAppVersion, String theUID,
    String theDeviceID, String theDormain, String theCarrierName,
    String theISOCountryCode, String theMobileCountryCode,
    String theMobileNetCode, LDNetDiagnoListener theListener) {
  super();
  this._context = context;
  this._appCode = theAppCode;
  this._appName = theAppName;
  this._appVersion = theAppVersion;
  this._UID = theUID;
  this._deviceID = theDeviceID;
  this._dormain = theDormain;
  this._carrierName = theCarrierName;
  this._ISOCountryCode = theISOCountryCode;
  this._MobileCountryCode = theMobileCountryCode;
  this._MobileNetCode = theMobileNetCode;
  this._netDiagnolistener = theListener;
  //
  this._isRunning = false;
  _remoteIpList = new ArrayList<String>();
  _telManager = (TelephonyManager) context
      .getSystemService(Context.TELEPHONY_SERVICE);
  sExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE,
      KEEP_ALIVE, TimeUnit.SECONDS, sWorkQueue, sThreadFactory);

}
 
Example 13
Source File: Log4j2AppenderComparisonBenchmark.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.SECONDS)
@Benchmark
public void appenderFile() {
    fileAppender.append(EVENT);
}
 
Example 14
Source File: RenewNodeTask.java    From sofa-registry with Apache License 2.0 4 votes vote down vote up
@Override
public TimeUnit getTimeUnit() {
    return TimeUnit.SECONDS;
}
 
Example 15
Source File: FailoverLoop.java    From mariadb-connector-j with GNU Lesser General Public License v2.1 4 votes vote down vote up
public FailoverLoop(ScheduledExecutorService scheduler) {
  super(scheduler, 1, 1, TimeUnit.SECONDS);
}
 
Example 16
Source File: SitemapsRecrawlSelector.java    From ache with Apache License 2.0 4 votes vote down vote up
public SitemapsRecrawlSelector() {
    this(30, TimeUnit.SECONDS);
}
 
Example 17
Source File: Duration.java    From lyra with Apache License 2.0 4 votes vote down vote up
/**
 * Returns a Duration of {@code count} seconds.
 */
public static Duration secs(long count) {
  return new Duration(count, TimeUnit.SECONDS);
}
 
Example 18
Source File: DefaultRetryStrategy.java    From aliyun-tablestore-java-sdk with Apache License 2.0 4 votes vote down vote up
public DefaultRetryStrategy() {
    this(10, TimeUnit.SECONDS);
}
 
Example 19
Source File: JpaAppenderBenchmark.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.SECONDS)
@Benchmark
public void testThroughputH2Exception(final Blackhole bh) {
    loggerH2.warn("Test message", exception);
}
 
Example 20
Source File: Configuration.java    From flink with Apache License 2.0 votes vote down vote up
TimeUnit unit() { return TimeUnit.SECONDS; }