aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/de/pixart/messenger/utils/SerialSingleThreadExecutor.java
blob: 116149ec1c43cbad2d1e886d6db2db4387746264 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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);
		}
	}
}