1package eu.siacs.conversations.utils;
2
3import android.os.Looper;
4
5import java.util.ArrayDeque;
6import java.util.Queue;
7import java.util.concurrent.Executor;
8import java.util.concurrent.Executors;
9
10import eu.siacs.conversations.services.AttachFileToConversationRunnable;
11
12public class SerialSingleThreadExecutor implements Executor {
13
14 final Executor executor = Executors.newSingleThreadExecutor();
15 protected final ArrayDeque<Runnable> tasks = new ArrayDeque<>();
16 private Runnable active;
17
18 public SerialSingleThreadExecutor() {
19 this(false);
20 }
21
22 public SerialSingleThreadExecutor(boolean prepareLooper) {
23 if (prepareLooper) {
24 execute(new Runnable() {
25 @Override
26 public void run() {
27 Looper.prepare();
28 }
29 });
30 }
31 }
32
33 public synchronized void execute(final Runnable r) {
34 tasks.offer(new Runnable() {
35 public void run() {
36 try {
37 r.run();
38 } finally {
39 scheduleNext();
40 }
41 }
42 });
43 if (active == null) {
44 scheduleNext();
45 }
46 }
47
48 protected synchronized void scheduleNext() {
49 if ((active = tasks.poll()) != null) {
50 executor.execute(active);
51 }
52 }
53}