Java Code Examples for org.rapidoid.u.U#time()

The following examples show how to use org.rapidoid.u.U#time() . 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: ExpirationCrawlerThread.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
private void crawl() {
	for (Iterable<? extends Expiring> coll : Coll.copyOf(collections)) {
		long now = U.time();

		for (Expiring target : coll) {

			try {
				long expiresAt = target.getExpiresAt();

				if (expiresAt > 0 && expiresAt < now) {
					target.expire();
					target.setExpiresAt(0);
				}

			} catch (Exception e) {
				Log.error("Error on expiration!", e);
			}
		}
	}
}
 
Example 2
Source File: FutureImpl.java    From rapidoid with Apache License 2.0 6 votes vote down vote up
@Override
public T get(long timeoutMs, long sleepingIntervalMs) throws TimeoutException {
	long waitingSince = U.time();

	while (!isDone()) {
		if (U.timedOut(waitingSince, timeoutMs)) {
			throw new TimeoutException();
		}

		U.sleep(sleepingIntervalMs);
	}

	if (getError() != null) {
		throw U.rte("Cannot get the result, there was an error!", error);
	}

	return result;
}
 
Example 3
Source File: ConnectionTarget.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
public ConnectionTarget(SocketChannel socketChannel, InetSocketAddress addr, Protocol protocol,
                        ChannelHolderImpl holder, boolean reconnecting, ConnState state) {

	U.notNull(protocol, "connection protocol");
	U.notNull(holder, "connection holder");

	this.socketChannel = socketChannel;
	this.addr = addr;
	this.protocol = protocol;
	this.retryAfter = U.time();
	this.holder = holder;
	this.reconnecting = reconnecting;
	this.state = state;
}
 
Example 4
Source File: ExpirationCrawlerThread.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
	long startedAt = U.time();

	while (!Thread.interrupted()) {

		long timeSpent = U.time() - startedAt;
		U.sleep(Math.max(resolution - timeSpent, 0));
		startedAt = U.time();

		crawl();
	}
}
 
Example 5
Source File: RespImpl.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
@Override
public void authorize(UserInfo user) {
	Ctxs.required().setUser(user);

	req.token().put(Tokens._USER, user.username);

	long ttl = Conf.TOKEN.entry("ttl").or(0);
	long expiresOn = ttl > 0 ? U.time() + ttl : Long.MAX_VALUE;
	req.token().put(Tokens._EXPIRES, expiresOn);

	req.tokenChanged.set(true);
}
 
Example 6
Source File: Res.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
protected byte[] load(String filename) {
	File file = IO.file(filename);

	if (file.exists()) {

		if (!file.isFile() || file.isDirectory()) {
			return null;
		}

		// a normal file on the file system
		Log.trace("Resource file exists", "name", name, "file", file);

		long lastModif;
		try {
			lastModif = Files.getLastModifiedTime(file.toPath()).to(TimeUnit.MILLISECONDS);

		} catch (IOException e) {
			// maybe it doesn't exist anymore
			lastModif = U.time();
		}

		if (lastModif > this.lastModified || !filename.equals(cachedFileName)) {
			Log.debug("Loading resource file", "name", name, "file", file);
			this.lastModified = file.lastModified();
			this.hidden = file.isHidden();
			return IO.loadBytes(filename);

		} else {
			Log.trace("Resource file not modified", "name", name, "file", file);
			return bytes;
		}

	} else {
		// it might not exist or it might be on the classpath or compressed in a JAR
		Log.trace("Trying to load classpath resource", "name", name, "file", file);
		this.hidden = false;
		return IO.loadBytes(filename);
	}
}
 
Example 7
Source File: Msc.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
public static void benchmarkComplete(String name, int count, long startTime) {

		long end = U.time();
		long ms = end - startTime;

		if (ms == 0) {
			ms = 1;
		}

		double avg = ((double) count / (double) ms);

		String avgs;

		if (avg > 1) {
			if (avg < 1000) {
				avgs = Math.round(avg) + "K";
			} else {
				avgs = Math.round(avg / 100) / 10.0 + "M";
			}
		} else {
			avgs = Math.round(avg * 1000) + "";
		}

		String data = String.format("%s: %s in %s ms (%s/sec)", name, count, ms, avgs);

		Log.info(data + " | " + Insights.getCpuMemStats());
	}
 
Example 8
Source File: Msc.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
public static void doBenchmark(String name, int count, BenchmarkOperation operation, boolean silent) {
	long start = U.time();

	for (int i = 0; i < count; i++) {
		operation.run(i);
	}

	if (!silent) {
		benchmarkComplete(name, count, start);
	}
}
 
Example 9
Source File: ConcurrentCacheAtom.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
/**
 * Sets new cached value, executes inside already acquired write lock.
 */
private V setValueInsideWriteLock(V newValue) {
	CachedValue<V> cached = cachedValue; // read the cached value
	V oldValue = cached != null ? cached.value : null;

	if (newValue != null) {
		long expiresAt = ttlInMs > 0 ? U.time() + ttlInMs : Long.MAX_VALUE;
		cachedValue = new CachedValue<>(newValue, expiresAt);

	} else {
		cachedValue = null;
	}

	return oldValue;
}
 
Example 10
Source File: JdbcWorker.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
@Override
protected void loop() throws Exception {

	Connection conn = null;

	try {

		long since = 0;

		do {
			Operation<Connection> op = queue.poll();

			if (op != null) {

				if (conn == null) {
					// first op
					conn = jdbc.getConnection();
					since = U.time();
				}

				op.execute(conn);

			} else {
				U.sleep(1);
				break;
			}

		} while (U.timedOut(since, batchTimeMs));

	} catch (Exception e) {
		Log.error("JDBC worker operation error!", e);

	} finally {
		if (conn != null) {
			conn.close();
		}
	}
}
 
Example 11
Source File: ClasspathScanner.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
private static List<String> scanClasses(ScanParams params) {
	String[] pkgs = params.in();

	String rootPackage = ClasspathUtil.getRootPackage();
	if (U.isEmpty(pkgs)) {
		pkgs = rootPackage != null ? new String[]{rootPackage} : new String[]{""};
	}

	long startingAt = U.time();

	String regex = params.matching();
	Pattern pattern = U.notEmpty(regex) ? Pattern.compile(regex) : null;

	if (regex != null) {
		Log.info("Scanning classpath", "!annotated", Msc.annotations(params.annotated()), "!packages", Arrays.toString(pkgs), "!matching", regex);
	} else {
		Log.info("Scanning classpath", "!annotated", Msc.annotations(params.annotated()), "!packages", Arrays.toString(pkgs));
	}

	Set<String> classpath = U.notEmpty(params.classpath()) ? U.set(params.classpath()) : ClasspathUtil.getClasspath();
	AtomicInteger searched = new AtomicInteger();
	Set<String> classes = U.set();

	for (String pkg : pkgs) {
		classes.addAll(retrieveClasses(classpath, pkg, params.annotated(), params.bytecodeFilter(), pattern, params.classLoader(), searched));
	}

	List<String> classList = U.list(classes);

	long timeMs = U.time() - startingAt;

	Log.info("Finished classpath scan", "time", Msc.maybeMasked(timeMs) + "ms", "searched", searched.get(), "!found", Msc.classNames(classList));

	return classList;
}
 
Example 12
Source File: Msc.java    From rapidoid with Apache License 2.0 4 votes vote down vote up
public static void benchmarkMT(int threadsN, final String name, final int count, final CountDownLatch outsideLatch,
                               final BenchmarkOperation operation) {

	U.must(count % threadsN == 0, "The number of thread must be a factor of the total count!");
	final int countPerThread = count / threadsN;

	final CountDownLatch latch = outsideLatch != null ? outsideLatch : new CountDownLatch(threadsN);

	long time = U.time();

	final Ctx ctx = Ctxs.get();

	for (int i = 1; i <= threadsN; i++) {
		new RapidoidThread() {

			@Override
			public void run() {
				Ctxs.attach(ctx != null ? ctx.span() : null);

				try {
					doBenchmark(name, countPerThread, operation, true);
					if (outsideLatch == null) {
						latch.countDown();
					}

				} finally {
					if (ctx != null) {
						Ctxs.close();
					}
				}
			}

		}.start();
	}

	try {
		latch.await();
	} catch (InterruptedException e) {
		throw U.rte(e);
	}

	benchmarkComplete("avg(" + name + ")", threadsN * countPerThread, time);
}
 
Example 13
Source File: Msc.java    From rapidoid with Apache License 2.0 4 votes vote down vote up
public static void startMeasure() {
	state.measureStart = U.time();
}
 
Example 14
Source File: Msc.java    From rapidoid with Apache License 2.0 4 votes vote down vote up
public static void endMeasure() {
	long delta = U.time() - state.measureStart;
	Log.info("Benchmark", "time", delta + " ms");
}
 
Example 15
Source File: Msc.java    From rapidoid with Apache License 2.0 4 votes vote down vote up
public static void endMeasure(String info) {
	long delta = U.time() - state.measureStart;
	Log.info("Benchmark", "info", info, "time", delta + " ms");
}
 
Example 16
Source File: Msc.java    From rapidoid with Apache License 2.0 4 votes vote down vote up
public static void endMeasure(long count, String info) {
	long delta = U.time() - state.measureStart;
	long freq = Math.round(1000 * (double) count / delta);
	Log.info("Benchmark", "performance", U.frmt("%s %s in %s ms (%s/sec)", count, info, delta, freq));
}
 
Example 17
Source File: ExtendedWorker.java    From rapidoid with Apache License 2.0 4 votes vote down vote up
private void retryConnecting(ConnectionTarget target) throws IOException {
	Log.warn("Reconnecting...", "address", target.addr);
	target.socketChannel = SocketChannel.open();
	target.retryAfter = U.time() + 1000;
	connect(target);
}
 
Example 18
Source File: Usage.java    From rapidoid with Apache License 2.0 4 votes vote down vote up
public static void touchLastAppUsedOn() {
	lastAppUsedOn = U.time();
}
 
Example 19
Source File: TUUID.java    From rapidoid with Apache License 2.0 4 votes vote down vote up
public TUUID() {
	UUID uuid = UUID.randomUUID();
	this.time = U.time();
	this.uuidHigh = uuid.getMostSignificantBits();
	this.uuidLow = uuid.getLeastSignificantBits();
}
 
Example 20
Source File: RapidoidInfo.java    From rapidoid with Apache License 2.0 4 votes vote down vote up
public static long uptime() {
	return U.time() - startedOn;
}