org.neo4j.test.ThreadTestUtils Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of test-utils Show documentation
Show all versions of test-utils Show documentation
A set of utilities used by tests.
/*
* Copyright (c) "Neo4j"
* Neo4j Sweden AB [https://neo4j.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
package org.neo4j.test;
import java.util.EnumSet;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.function.Predicate;
public class ThreadTestUtils {
private ThreadTestUtils() {}
public static Thread fork(Runnable runnable) {
String name = "Forked-from-" + Thread.currentThread().getName();
Thread thread = new Thread(runnable, name);
thread.setDaemon(true);
thread.start();
return thread;
}
public static Future forkFuture(Callable callable) {
FutureTask task = new FutureTask<>(callable);
fork(task);
return task;
}
public static void awaitThreadState(Thread thread, long maxWaitMillis, Thread.State first, Thread.State... rest) {
awaitThreadState(thread, maxWaitMillis, s -> true, first, rest);
}
public static void awaitThreadState(
Thread thread,
long maxWaitMillis,
Predicate positionFilter,
Thread.State first,
Thread.State... rest) {
EnumSet set = EnumSet.of(first, rest);
long deadline = maxWaitMillis + System.currentTimeMillis();
Thread.State currentState;
do {
currentState = thread.getState();
if (System.currentTimeMillis() > deadline) {
throw new AssertionError("Timed out waiting for thread state of <" + set + ">: " + thread + " (state = "
+ thread.getState() + ")");
}
} while (!set.contains(currentState) || !positionFilter.test(thread.getStackTrace()));
}
}