1package eu.siacs.conversations.utils;
2
3import java.util.ArrayDeque;
4import java.util.Queue;
5import java.util.concurrent.Executor;
6import java.util.concurrent.Executors;
7
8public class SerialSingleThreadExecutor implements Executor {
9
10 final Executor executor = Executors.newSingleThreadExecutor();
11 final Queue<Runnable> tasks = new ArrayDeque();
12 Runnable active;
13
14 public synchronized void execute(final Runnable r) {
15 tasks.offer(new Runnable() {
16 public void run() {
17 try {
18 r.run();
19 } finally {
20 scheduleNext();
21 }
22 }
23 });
24 if (active == null) {
25 scheduleNext();
26 }
27 }
28
29 protected synchronized void scheduleNext() {
30 if ((active = tasks.poll()) != null) {
31 executor.execute(active);
32 }
33 }
34}