aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/de/pixart/messenger/utils/SerialSingleThreadExecutor.java
diff options
context:
space:
mode:
Diffstat (limited to 'src/main/java/de/pixart/messenger/utils/SerialSingleThreadExecutor.java')
-rw-r--r--src/main/java/de/pixart/messenger/utils/SerialSingleThreadExecutor.java51
1 files changed, 51 insertions, 0 deletions
diff --git a/src/main/java/de/pixart/messenger/utils/SerialSingleThreadExecutor.java b/src/main/java/de/pixart/messenger/utils/SerialSingleThreadExecutor.java
new file mode 100644
index 000000000..116149ec1
--- /dev/null
+++ b/src/main/java/de/pixart/messenger/utils/SerialSingleThreadExecutor.java
@@ -0,0 +1,51 @@
+package de.pixart.messenger.utils;
+
+import android.os.Looper;
+
+import java.util.ArrayDeque;
+import java.util.Queue;
+import java.util.concurrent.Executor;
+import java.util.concurrent.Executors;
+
+public class SerialSingleThreadExecutor implements Executor {
+
+ final Executor executor = Executors.newSingleThreadExecutor();
+ protected final Queue<Runnable> tasks = new ArrayDeque();
+ Runnable active;
+
+ public SerialSingleThreadExecutor() {
+ this(false);
+ }
+
+ public SerialSingleThreadExecutor(boolean prepareLooper) {
+ if (prepareLooper) {
+ execute(new Runnable() {
+ @Override
+ public void run() {
+ Looper.prepare();
+ }
+ });
+ }
+ }
+
+ public synchronized void execute(final Runnable r) {
+ tasks.offer(new Runnable() {
+ public void run() {
+ try {
+ r.run();
+ } finally {
+ scheduleNext();
+ }
+ }
+ });
+ if (active == null) {
+ scheduleNext();
+ }
+ }
+
+ protected synchronized void scheduleNext() {
+ if ((active = tasks.poll()) != null) {
+ executor.execute(active);
+ }
+ }
+} \ No newline at end of file