Add ExecutableRunnable
[fonbot.git] / src / ro / ieval / fonbot / ExecutableRunnable.java
1 package ro.ieval.fonbot;
2
3 import java.util.LinkedList;
4 import java.util.Queue;
5 import java.util.concurrent.Executor;
6 import java.util.concurrent.Executors;
7
8 /*
9 * Copyright © 2013 Marius Gavrilescu
10 *
11 * This file is part of FonBot.
12 *
13 * FonBot is free software: you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation, either version 3 of the License, or
16 * (at your option) any later version.
17 *
18 * FonBot is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
22 *
23 * You should have received a copy of the GNU General Public License
24 * along with FonBot. If not, see <http://www.gnu.org/licenses/>.
25 */
26
27 /**
28 * Slim alternative to AsyncTask.<p>
29 *
30 * Differences from AsyncTask:
31 * <ul>
32 * <li>No onPreExecute or onPostExecute
33 * <li>No progress support
34 * <li>Can be retried if necessary
35 * </ul>
36 *
37 * @author Marius Gavrilescu <marius@ieval.ro>
38 */
39 abstract class ExecutableRunnable implements Runnable {
40 /** Executor used to execute instances of this class */
41 private static final Executor executor = Executors.newSingleThreadExecutor();
42 /** Queue containing <code>ExecutableRunnable</code>s that should be retried */
43 private static final Queue<ExecutableRunnable> retryPendingTasks = new LinkedList<ExecutableRunnable>();
44
45 /** Run all tasks that should be retried */
46 public static final void retryTasks(){
47 synchronized(retryPendingTasks){
48 for(ExecutableRunnable task : retryPendingTasks)
49 task.execute();
50 retryPendingTasks.clear();
51 }
52 }
53
54 /** Execute this <code>ExecutableRunnable</code> */
55 public final void execute(){
56 retryTasks();
57 executor.execute(this);
58 }
59
60 /** Mark this <code>ExecutableRunnable</code> as needing to be retried later */
61 protected final void retry(){
62 synchronized(retryPendingTasks){
63 retryPendingTasks.add(this);
64 }
65 }
66 }
This page took 0.022198 seconds and 4 git commands to generate.