From bf70dcc30a9bd5cbcd71aa8481f7171331f9f1b6 Mon Sep 17 00:00:00 2001 From: Marius Gavrilescu Date: Tue, 12 Mar 2013 18:16:34 +0200 Subject: [PATCH] Add ExecutableRunnable ExecutableRunnable is a lightweight replacement for AsyncTask. It does not support onPreExecute()/onPostExecute() or showing progress, but it can be ran multiple times and retried if it fails. --- src/ro/ieval/fonbot/ExecutableRunnable.java | 66 +++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 src/ro/ieval/fonbot/ExecutableRunnable.java diff --git a/src/ro/ieval/fonbot/ExecutableRunnable.java b/src/ro/ieval/fonbot/ExecutableRunnable.java new file mode 100644 index 0000000..642661b --- /dev/null +++ b/src/ro/ieval/fonbot/ExecutableRunnable.java @@ -0,0 +1,66 @@ +package ro.ieval.fonbot; + +import java.util.LinkedList; +import java.util.Queue; +import java.util.concurrent.Executor; +import java.util.concurrent.Executors; + +/* + * Copyright © 2013 Marius Gavrilescu + * + * This file is part of FonBot. + * + * FonBot is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * FonBot is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with FonBot. If not, see . + */ + +/** + * Slim alternative to AsyncTask.

+ * + * Differences from AsyncTask: + *

+ * + * @author Marius Gavrilescu + */ +abstract class ExecutableRunnable implements Runnable { + /** Executor used to execute instances of this class */ + private static final Executor executor = Executors.newSingleThreadExecutor(); + /** Queue containing ExecutableRunnables that should be retried */ + private static final Queue retryPendingTasks = new LinkedList(); + + /** Run all tasks that should be retried */ + public static final void retryTasks(){ + synchronized(retryPendingTasks){ + for(ExecutableRunnable task : retryPendingTasks) + task.execute(); + retryPendingTasks.clear(); + } + } + + /** Execute this ExecutableRunnable */ + public final void execute(){ + retryTasks(); + executor.execute(this); + } + + /** Mark this ExecutableRunnable as needing to be retried later */ + protected final void retry(){ + synchronized(retryPendingTasks){ + retryPendingTasks.add(this); + } + } +} -- 2.39.2