mirror of
https://github.com/signalapp/Signal-Android.git
synced 2025-12-24 04:58:45 +00:00
Make thread related utility methods available for use in all modules.
This commit is contained in:
90
core-util/src/main/java/org/signal/core/util/ThreadUtil.java
Normal file
90
core-util/src/main/java/org/signal/core/util/ThreadUtil.java
Normal file
@@ -0,0 +1,90 @@
|
||||
package org.signal.core.util;
|
||||
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
|
||||
/**
|
||||
* Thread related utility functions.
|
||||
*/
|
||||
public final class ThreadUtil {
|
||||
|
||||
private static volatile Handler handler;
|
||||
|
||||
private ThreadUtil() {}
|
||||
|
||||
private static Handler getHandler() {
|
||||
if (handler == null) {
|
||||
synchronized (ThreadUtil.class) {
|
||||
if (handler == null) {
|
||||
handler = new Handler(Looper.getMainLooper());
|
||||
}
|
||||
}
|
||||
}
|
||||
return handler;
|
||||
}
|
||||
|
||||
public static boolean isMainThread() {
|
||||
return Looper.myLooper() == Looper.getMainLooper();
|
||||
}
|
||||
|
||||
public static void assertMainThread() {
|
||||
if (!isMainThread()) {
|
||||
throw new AssertionError("Must run on main thread.");
|
||||
}
|
||||
}
|
||||
|
||||
public static void assertNotMainThread() {
|
||||
if (isMainThread()) {
|
||||
throw new AssertionError("Cannot run on main thread.");
|
||||
}
|
||||
}
|
||||
|
||||
public static void postToMain(final @NonNull Runnable runnable) {
|
||||
getHandler().post(runnable);
|
||||
}
|
||||
|
||||
public static void runOnMain(final @NonNull Runnable runnable) {
|
||||
if (isMainThread()) runnable.run();
|
||||
else getHandler().post(runnable);
|
||||
}
|
||||
|
||||
public static void runOnMainDelayed(final @NonNull Runnable runnable, long delayMillis) {
|
||||
getHandler().postDelayed(runnable, delayMillis);
|
||||
}
|
||||
|
||||
public static void cancelRunnableOnMain(@NonNull Runnable runnable) {
|
||||
getHandler().removeCallbacks(runnable);
|
||||
}
|
||||
|
||||
public static void runOnMainSync(final @NonNull Runnable runnable) {
|
||||
if (isMainThread()) {
|
||||
runnable.run();
|
||||
} else {
|
||||
final CountDownLatch sync = new CountDownLatch(1);
|
||||
runOnMain(() -> {
|
||||
try {
|
||||
runnable.run();
|
||||
} finally {
|
||||
sync.countDown();
|
||||
}
|
||||
});
|
||||
try {
|
||||
sync.await();
|
||||
} catch (InterruptedException ie) {
|
||||
throw new AssertionError(ie);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void sleep(long millis) {
|
||||
try {
|
||||
Thread.sleep(millis);
|
||||
} catch (InterruptedException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user