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

The following are Jave code examples for showing how to use SECONDS of the java.util.concurrent.TimeUnit class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: GuancialeDB   File: GuancialeDBBenchmark.java   View Source Code Vote up 6 votes
@Benchmark
@Warmup(iterations = 10)
@Measurement(iterations = 10)
@Fork(1)
@Threads(1)
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.SECONDS)
public int measureCreateEmptyNodesAndRelationships() throws IOException {
    int user;
    for (user = 0; user < userCount; user++) {
        db.addNode("user" + user);
    }
    for (user = 0; user < userCount; user++) {
        for (int like = 0; like < friendsCount; like++) {
            db.addRelationship("FRIENDS", "user" + user, "user" + rand.nextInt(userCount));
        }
    }
    return user;
}
 
Example 2
Project: monarch   File: SerializableTimeoutTest.java   View Source Code Vote up 6 votes
@Test
public void canBeSerialized() throws Exception {
  long timeout = 2;
  TimeUnit timeUnit = TimeUnit.SECONDS;
  boolean lookingForStuckThread = true;

  SerializableTimeout instance = SerializableTimeout.builder().withTimeout(timeout, timeUnit)
      .withLookingForStuckThread(lookingForStuckThread).build();

  assertThat(readField(Timeout.class, instance, FIELD_TIMEOUT)).isEqualTo(timeout);
  assertThat(readField(Timeout.class, instance, FIELD_TIME_UNIT)).isEqualTo(timeUnit);
  assertThat(readField(Timeout.class, instance, FIELD_LOOK_FOR_STUCK_THREAD))
      .isEqualTo(lookingForStuckThread);

  SerializableTimeout cloned = (SerializableTimeout) SerializationUtils.clone(instance);

  assertThat(readField(Timeout.class, cloned, FIELD_TIMEOUT)).isEqualTo(timeout);
  assertThat(readField(Timeout.class, cloned, FIELD_TIME_UNIT)).isEqualTo(timeUnit);
  assertThat(readField(Timeout.class, cloned, FIELD_LOOK_FOR_STUCK_THREAD))
      .isEqualTo(lookingForStuckThread);
}
 
Example 3
Project: GuancialeDB   File: GuancialeDBBenchmark.java   View Source Code Vote up 6 votes
@Benchmark
@Warmup(iterations = 10)
@Measurement(iterations = 10)
@Fork(1)
@Threads(4)
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.SECONDS)
public int measureCreateNodesWithProperties() throws IOException {
    int user;
    for (user = 0; user < userCount; user++) {
        HashMap<String, Object> properties = new HashMap<>();
        properties.put("username", "username" + rand.nextInt() );
        properties.put("age", + rand.nextInt(100) );
        properties.put("weight", rand.nextInt(300) );
        db.addNode( String.valueOf(rand.nextInt()), properties);
    }
    return user;
}
 
Example 4
Project: csap-core   File: LogRollerRunnable.java   View Source Code Vote up 6 votes
public LogRollerRunnable( Application csapApp ) {

		this.csapApp = csapApp;

		long initialDelay = 5;
		long interval = csapApp.lifeCycleSettings().getLogRotationMinutes();

		TimeUnit logRotationTimeUnit = TimeUnit.MINUTES;

		if ( Application.isRunningOnDesktop() ) {
			logger.warn( "Setting DESKTOP to seconds" );
			logRotationTimeUnit = TimeUnit.SECONDS;
		}

		logger.warn(
			"Scheduling logrotates to be triggered every {} {}. Logs only rotated if size exceeds threshold (default is 10mb)",
			interval, logRotationTimeUnit );

		ScheduledFuture<?> jobHandle = scheduledExecutorService
			.scheduleAtFixedRate(
				() -> executeLogRotateForAllServices(),
				initialDelay,
				interval,
				logRotationTimeUnit );

	}
 
Example 5
Project: monarch   File: ScheduledThreadPoolExecutorWithKeepAliveJUnitTest.java   View Source Code Vote up 6 votes
@Test
public void testShutdown2() throws InterruptedException {
  ex = new ScheduledThreadPoolExecutorWithKeepAlive(50, 1, TimeUnit.SECONDS,
      Executors.defaultThreadFactory());
  ex.submit(new Runnable() {
    public void run() {
      try {
        Thread.sleep(3000);
      } catch (InterruptedException e) {
        fail("interrupted");
      }
    }
  });
  // give it a chance to get in the worker pool
  Thread.sleep(500);
  ex.shutdown();
  long start = System.nanoTime();
  assertTrue(ex.awaitTermination(10, TimeUnit.SECONDS));
  long elapsed = System.nanoTime() - start;
  assertTrue("Shutdown did not wait to task to complete. Only waited "
      + TimeUnit.NANOSECONDS.toMillis(elapsed), TimeUnit.SECONDS.toNanos(2) < elapsed);
}
 
Example 6
Project: L2jBrasil   File: ThreadPoolManager.java   View Source Code Vote up 5 votes
private ThreadPoolManager()
{
	_effectsScheduledThreadPool = new ScheduledThreadPoolExecutor(Config.THREAD_P_EFFECTS, new PriorityThreadFactory("EffectsSTPool", Thread.NORM_PRIORITY));
	_generalScheduledThreadPool = new ScheduledThreadPoolExecutor(Config.THREAD_P_GENERAL, new PriorityThreadFactory("GerenalSTPool", Thread.NORM_PRIORITY));
	_ioPacketsThreadPool = new ThreadPoolExecutor(Config.IO_PACKET_THREAD_CORE_SIZE, Integer.MAX_VALUE,5L, TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>(),new PriorityThreadFactory("I/O Packet Pool",Thread.NORM_PRIORITY+1));
	_generalPacketsThreadPool = new ThreadPoolExecutor(Config.GENERAL_PACKET_THREAD_CORE_SIZE, Config.GENERAL_PACKET_THREAD_CORE_SIZE+2,15L, TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>(),new PriorityThreadFactory("Normal Packet Pool",Thread.NORM_PRIORITY+1));
	_generalThreadPool = new ThreadPoolExecutor(Config.GENERAL_THREAD_CORE_SIZE, Config.GENERAL_THREAD_CORE_SIZE+2,5L, TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>(),new PriorityThreadFactory("General Pool",Thread.NORM_PRIORITY));
	// will be really used in the next AI implementation.
	_aiThreadPool = new ThreadPoolExecutor(1, Config.AI_MAX_THREAD,10L, TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>());
	_aiScheduledThreadPool = new ScheduledThreadPoolExecutor(Config.AI_MAX_THREAD, new PriorityThreadFactory("AISTPool", Thread.NORM_PRIORITY));
}
 
Example 7
Project: GuancialeDB   File: GuancialeDBBenchmark.java   View Source Code Vote up 5 votes
@Benchmark
@Warmup(iterations = 10)
@Measurement(iterations = 10)
@Fork(1)
@Threads(4)
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.SECONDS)
public void measureSingleTraversal() throws IOException {
    db.getOutgoingRelationshipNodeIds("LIKES", "person" + rand.nextInt(personCount));
}
 
Example 8
Project: monarch   File: ScheduledThreadPoolExecutorWithKeepAliveJUnitTest.java   View Source Code Vote up 5 votes
@Test
public void testConcurrentRepeatedTasks() throws InterruptedException, ExecutionException {
  ex = new ScheduledThreadPoolExecutorWithKeepAlive(50, 1, TimeUnit.SECONDS,
      Executors.defaultThreadFactory());

  final AtomicInteger counter = new AtomicInteger();
  Runnable waitForABit = new Runnable() {
    public void run() {
      try {
        counter.incrementAndGet();
        Thread.sleep(500);
      } catch (InterruptedException e) {
        fail("interrupted");
      }
    }
  };

  Future[] futures = new Future[50];
  for (int i = 0; i < 50; i++) {
    futures[i] = ex.scheduleAtFixedRate(waitForABit, 0, 1, TimeUnit.SECONDS);
  }

  Thread.sleep(10000);

  for (int i = 0; i < 50; i++) {
    futures[i].cancel(true);
  }

  System.err.println("Counter = " + counter);
  assertTrue("Tasks did not execute in parallel. Expected more than 300 executions, got "
      + counter.get(), counter.get() > 300);

  assertEquals(50, ex.getLargestPoolSize());

  // now make sure we expire back down.
  Thread.sleep(5000);
  assertEquals(1, ex.getPoolSize());
}
 
Example 9
Project: RxJava3-preview   File: TimedTest.java   View Source Code Vote up 5 votes
@Test
public void properties() {
    Timed<Integer> timed = new Timed<Integer>(1, 5, TimeUnit.SECONDS);

    assertEquals(1, timed.value().intValue());
    assertEquals(5, timed.time());
    assertEquals(5000, timed.time(TimeUnit.MILLISECONDS));
    assertSame(TimeUnit.SECONDS, timed.unit());
}
 
Example 10
Project: lams   File: ResponseTimeAttribute.java   View Source Code Vote up 5 votes
@Override
public ExchangeAttribute build(String token) {
    if (token.equals(RESPONSE_TIME_MILLIS) || token.equals(RESPONSE_TIME_MILLIS_SHORT)) {
        return new ResponseTimeAttribute(TimeUnit.MILLISECONDS);
    }
    if (token.equals(RESPONSE_TIME_SECONDS_SHORT)) {
        return new ResponseTimeAttribute(TimeUnit.SECONDS);
    }
    return null;
}
 
Example 11
Project: lazycat   File: ContainerBase.java   View Source Code Vote up 5 votes
@Override
protected void initInternal() throws LifecycleException {
	BlockingQueue<Runnable> startStopQueue = new LinkedBlockingQueue<Runnable>();
	startStopExecutor = new ThreadPoolExecutor(getStartStopThreadsInternal(), getStartStopThreadsInternal(), 10,
			TimeUnit.SECONDS, startStopQueue, new StartStopThreadFactory(getName() + "-startStop-"));
	startStopExecutor.allowCoreThreadTimeOut(true);
	super.initInternal();
}
 
Example 12
Project: AssistantBySDK   File: DownloadTask.java   View Source Code Vote up 5 votes
/**
 * 构建文件下载器,适用于下载单个大文件
 *
 * @param downloadUrl 下载路径
 * @param fileSaveDir 文件保存目录
 * @param threadNum   下载线程数
 */
public DownloadTask(Context context, String downloadUrl, File fileSaveDir, int threadNum) {
    try {
        System.out.println("DownloadTask>>>" + downloadUrl);
        this.context = context;
        this.downloadUrl = downloadUrl;
        fileService = FileService.getInstance();
        URL url = new URL(this.downloadUrl);
        if (!fileSaveDir.exists())
            fileSaveDir.mkdirs();
        this.threadnum = threadNum;
        threadPool = new ThreadPoolExecutor(threadnum + 1, threadnum + 1, 20, TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>(), new ThreadPoolExecutor.CallerRunsPolicy());
        HttpURLConnection conn = getConnectionAndConnect(url, 3);
        this.fileSize = conn.getContentLength();//根据响应获取文件大小
        if (this.fileSize <= 0)
            throw new RuntimeException("Unkown file size ");

        String filename = getFileName(conn);
        this.saveFile = new File(fileSaveDir, filename);/* 保存文件 */
        Map<Integer, Integer> logdata = fileService.getData(downloadUrl);
        if (logdata.size() > 0) {
            for (Map.Entry<Integer, Integer> entry : logdata.entrySet())
                data.put(entry.getKey(), entry.getValue());
        }
        this.block = (this.fileSize % threadnum) == 0 ? this.fileSize / threadnum : this.fileSize / threadnum + 1;
        if (this.data.size() == threadnum) {
            for (int i = 0; i < threadnum; i++) {
                this.downloadSize += this.data.get(i);
            }
            Log.i(TAG, "已经下载的长度" + this.downloadSize);
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("don't connection this url");
    }
}
 
Example 13
Project: game-executor   File: DisruptorTest.java   View Source Code Vote up 5 votes
public static void testUpdate() throws Exception {
        EventBus updateEventBus = new EventBus();
//        int maxSize = 10000;
//        int corePoolSize = 100;
        int maxSize = 20000;
        int corePoolSize = 20;
        long keepAliveTime = 60;
        TimeUnit timeUnit = TimeUnit.SECONDS;
        String poolName = "update";
        DisruptorExecutorService disruptorExcutorService = new DisruptorExecutorService(poolName, corePoolSize);
        int cycleSleepTime = 1000 / Constants.cycle.cycleSize;
        DisruptorDispatchThread dispatchThread = new DisruptorDispatchThread(updateEventBus, disruptorExcutorService
                , cycleSleepTime, cycleSleepTime*1000);
        disruptorExcutorService.setDisruptorDispatchThread(dispatchThread);
        UpdateService updateService = new UpdateService(dispatchThread, disruptorExcutorService);

        updateEventBus.addEventListener(new DispatchCreateEventListener(dispatchThread, updateService));
        updateEventBus.addEventListener(new DispatchUpdateEventListener(dispatchThread, updateService));
        updateEventBus.addEventListener(new DispatchFinishEventListener(dispatchThread, updateService));

//        updateService.notifyStart();
        updateService.start();
        long updateMaxSize = 100;
        for (long i = 0; i < maxSize; i++) {
            IntegerUpdate integerUpdate = new IntegerUpdate(i, updateMaxSize);
            EventParam<IntegerUpdate> param = new EventParam<IntegerUpdate>(integerUpdate);
            CycleEvent cycleEvent = new CycleEvent(Constants.EventTypeConstans.readyCreateEventType, integerUpdate.getUpdateId(), param);
            updateService.addReadyCreateEvent(cycleEvent);
        }


        while (true) {
            Thread.currentThread().sleep(100);
            updateService.toString();
        }

//        updateService.stop();
    }
 
Example 14
Project: util4j   File: QueuesExecutorService.java   View Source Code Vote up 4 votes
protected QueuesExecutorService(int corePoolSize, int maximumPoolSize,Queue<Runnable> bossQueue) {
    this(corePoolSize, maximumPoolSize, DEFAULT_KEEP_ALIVE_SEC, TimeUnit.SECONDS, 
    		Executors.defaultThreadFactory(),DEFAULT_waitConditionStrategy,
    		bossQueue,DEFAULT_IndexQueueGroupManager,DEFAULT_KeyQueueGroupManager,null);
}
 
Example 15
Project: jvm-dynamic-optimizations-performance-test   File: NMorphicInlinig.java   View Source Code Vote up 4 votes
@Measurement(iterations = 20000, time = 1, timeUnit = TimeUnit.SECONDS)
  @Benchmark
  public void testMethod(TestState s) throws Exception {
  	Calculator c = getCalculator(s);
s.valueSink = s.valueSink + handleRequest(c, 1312, 2435);
  }
 
Example 16
Project: fakeload   File: SimpleFakeLoadTest.java   View Source Code Vote up 4 votes
@Test(expected = IllegalArgumentException.class)
public void testIllegalArgumentCreation() {
    FakeLoad f1 = new SimpleFakeLoad(-1L, TimeUnit.SECONDS);
}
 
Example 17
Project: avaire   File: MusicActivityJob.java   View Source Code Vote up 4 votes
public MusicActivityJob(AvaIre avaire) {
    super(avaire, 30, 30, TimeUnit.SECONDS);
}
 
Example 18
Project: Subs   File: JobExecutor.java   View Source Code Vote up 4 votes
@Inject JobExecutor() {
    this.threadPoolExecutor =
            new ThreadPoolExecutor(NUMBER_OF_CORES * 2, NUMBER_OF_CORES * 2, 10L,
                    TimeUnit.SECONDS, new LinkedBlockingQueue<>(),
                    new JobThreadFactory());
}
 
Example 19
Project: boohee_v5.6   File: FramedConnection.java   View Source Code Vote up 4 votes
private FramedConnection(Builder builder) throws IOException {
    int i = 2;
    this.streams = new HashMap();
    this.idleStartTimeNs = System.nanoTime();
    this.unacknowledgedBytesRead = 0;
    this.okHttpSettings = new Settings();
    this.peerSettings = new Settings();
    this.receivedInitialPeerSettings = false;
    this.currentPushRequests = new LinkedHashSet();
    this.protocol = builder.protocol;
    this.pushObserver = builder.pushObserver;
    this.client = builder.client;
    this.listener = builder.listener;
    this.nextStreamId = builder.client ? 1 : 2;
    if (builder.client && this.protocol == Protocol.HTTP_2) {
        this.nextStreamId += 2;
    }
    if (builder.client) {
        i = 1;
    }
    this.nextPingId = i;
    if (builder.client) {
        this.okHttpSettings.set(7, 0, 16777216);
    }
    this.hostName = builder.hostName;
    if (this.protocol == Protocol.HTTP_2) {
        this.variant = new Http2();
        this.pushExecutor = new ThreadPoolExecutor(0, 1, 60, TimeUnit.SECONDS, new
                LinkedBlockingQueue(), Util.threadFactory(String.format("OkHttp %s Push " +
                "Observer", new Object[]{this.hostName}), true));
        this.peerSettings.set(7, 0, 65535);
        this.peerSettings.set(5, 0, 16384);
    } else if (this.protocol == Protocol.SPDY_3) {
        this.variant = new Spdy3();
        this.pushExecutor = null;
    } else {
        throw new AssertionError(this.protocol);
    }
    this.bytesLeftInWriteWindow = (long) this.peerSettings.getInitialWindowSize(65536);
    this.socket = builder.socket;
    this.frameWriter = this.variant.newWriter(builder.sink, this.client);
    this.readerRunnable = new Reader(this.variant.newReader(builder.source, this.client));
    new Thread(this.readerRunnable).start();
}
 
Example 20
Project: tascalate-concurrent   File: TaskExecutors.java   View Source Code Vote up 3 votes
/**
 * Creates a thread pool that creates new threads as needed, but will reuse
 * previously constructed threads when they are available, and uses the
 * provided ThreadFactory to create new threads when needed.
 * 
 * @param threadFactory
 *            the factory to use when creating new threads
 * @return the newly created thread pool
 * @throws NullPointerException
 *             if threadFactory is null
 */
public static TaskExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
    return new ThreadPoolTaskExecutor(0, Integer.MAX_VALUE, 
                                      60L, TimeUnit.SECONDS, 
                                      new SynchronousQueue<Runnable>(),
                                      threadFactory);
}