add TaskQueue interface to Map

- change AsyncTask to be able to post on main-thread
- rename Task.run() -> go()
This commit is contained in:
Hannes Janetzek 2014-04-20 00:24:26 +02:00
parent c161ea9cca
commit 64383a8406
10 changed files with 117 additions and 246 deletions

View File

@ -10,6 +10,7 @@ import com.badlogic.gdx.utils.Disposable;
*
*/
public class AsyncExecutor implements Disposable {
private final TaskQueue mainloop;
/**
* Creates a new AsynchExecutor that allows maxConcurrent {@link Runnable}
@ -17,32 +18,8 @@ public class AsyncExecutor implements Disposable {
*
* @param maxConcurrent
*/
public AsyncExecutor(int maxConcurrent) {
}
// FIXME TODO add wrap into 'FakeFuture' and run via Gdx.app.post()
/**
* Submits a {@link Runnable} to be executed asynchronously. If
* maxConcurrent runnables are already running, the runnable
* will be queued.
*
* @param task the task to execute asynchronously
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public <T> AsyncResult<T> submit(final AsyncTask<T> task) {
T result = null;
boolean error = false;
try {
task.run();
result = task.getResult();
} catch (Throwable t) {
error = true;
}
if (error)
return null;
return new AsyncResult(result);
public AsyncExecutor(int maxConcurrent, TaskQueue mainloop) {
this.mainloop = mainloop;
}
/**
@ -53,7 +30,12 @@ public class AsyncExecutor implements Disposable {
* @param task the task to execute asynchronously
*/
public boolean post(Runnable task) {
if (task instanceof AsyncTask) {
((AsyncTask) task).setTaskQueue(mainloop);
}
Gdx.app.postRunnable(task);
return true;
}

View File

@ -1,50 +0,0 @@
/*******************************************************************************
* Copyright 2013 See libgdx AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package org.oscim.utils.async;
//import java.util.concurrent.ExecutionException;
//import java.util.concurrent.Future;
/**
* Returned by {@link AsyncExecutor#submit(AsyncTask)}, allows to poll
* for the result of the asynch workload.
*
* @author badlogic
*
*/
public class AsyncResult<T> {
private final T result;
AsyncResult(T result) {
this.result = result;
}
/**
* @return whether the {@link AsyncTask} is done
*/
public boolean isDone() {
return true;
}
/**
* @return the result, or null if there was an error, no result, or the task
* is still running
*/
public T get() {
return result;
}
}

View File

@ -1,30 +0,0 @@
/*******************************************************************************
* Copyright 2013 See libgdx AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package org.oscim.utils.async;
/**
* Task to be submitted to an {@link AsyncExecutor}, returning a result of type
* T.
*
* @author badlogic
*
*/
public interface AsyncTask<T> extends Runnable {
public boolean cancel();
public T getResult() throws Exception;
}

View File

@ -1,28 +0,0 @@
/*******************************************************************************
* Copyright 2013 See libgdx AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package org.oscim.utils.async;
/**
* GWT emulation of ThreadUtils, does nothing.
*
* @author badlogic
*
*/
public class ThreadUtils {
public static void yield() {
}
}

View File

@ -33,10 +33,11 @@ import org.oscim.theme.ThemeFile;
import org.oscim.theme.ThemeLoader;
import org.oscim.tiling.TileSource;
import org.oscim.utils.async.AsyncExecutor;
import org.oscim.utils.async.TaskQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class Map {
public abstract class Map implements TaskQueue {
static final Logger log = LoggerFactory.getLogger(Map.class);
@ -111,7 +112,7 @@ public abstract class Map {
}
};
mAsyncExecutor = new AsyncExecutor(2);
mAsyncExecutor = new AsyncExecutor(4, this);
mMapPosition = new MapPosition();
mEventLayer = new MapEventLayer(this);
@ -194,6 +195,7 @@ public abstract class Map {
/**
* Post a runnable to be executed on main-thread
*/
@Override
public abstract boolean post(Runnable action);
/**
@ -203,9 +205,10 @@ public abstract class Map {
public abstract boolean postDelayed(Runnable action, long delay);
/**
* Post a task to run on a shared worker-thread. Only use for
* tasks running less than a second!
* Post a task to run on a shared worker-thread. Shoul only use for
* tasks running less than a second.
*/
@Override
public void addTask(Runnable task) {
mAsyncExecutor.post(task);
}

View File

@ -17,7 +17,6 @@
package org.oscim.utils.async;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
@ -37,6 +36,7 @@ import java.util.concurrent.TimeUnit;
*/
public class AsyncExecutor {
private final ExecutorService executor;
private final TaskQueue mainloop;
/**
* Creates a new AsynchExecutor that allows maxConcurrent {@link Runnable}
@ -44,7 +44,8 @@ public class AsyncExecutor {
*
* @param maxConcurrent number of threads.
*/
public AsyncExecutor(int maxConcurrent) {
public AsyncExecutor(int maxConcurrent, TaskQueue mainloop) {
this.mainloop = mainloop;
executor = Executors.newFixedThreadPool(maxConcurrent, new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
@ -63,25 +64,11 @@ public class AsyncExecutor {
*
* @param task the task to execute asynchronously
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public <T> AsyncResult<T> submit(final AsyncTask<T> task) {
return new AsyncResult(executor.submit(new Callable<T>() {
@Override
public T call() throws Exception {
task.run();
return task.getResult();
}
}));
public boolean post(Runnable task) {
if (task instanceof AsyncTask) {
((AsyncTask) task).setTaskQueue(mainloop);
}
/**
* Submits a {@link Runnable} to be executed asynchronously. If
* maxConcurrent runnables are already running, the runnable
* will be queued.
*
* @param task the task to execute asynchronously
*/
public boolean post(Runnable task) {
try {
executor.execute(task);
} catch (RejectedExecutionException e) {

View File

@ -1,54 +0,0 @@
/*******************************************************************************
* Copyright 2013 Mario Zechner <badlogicgames@gmail.com>
* Copyright 2013 Nathan Sweet <nathan.sweet@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package org.oscim.utils.async;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
/**
* Returned by {@link AsyncExecutor#submit(AsyncTask)}, allows to poll for the
* result of the asynch workload.
*
* @author badlogic
*/
public class AsyncResult<T> {
private final Future<T> future;
AsyncResult(Future<T> future) {
this.future = future;
}
/** @return whether the {@link AsyncTask} is done */
public boolean isDone() {
return future.isDone();
}
/**
* @return waits if necessary for the computation to complete and then
* returns the result
* @throws RuntimeException if there was an error
*/
public T get() {
try {
return future.get();
} catch (InterruptedException ex) {
return null;
} catch (ExecutionException ex) {
throw new RuntimeException(ex.getCause());
}
}
}

View File

@ -1,31 +1,58 @@
/*******************************************************************************
* Copyright 2013 Mario Zechner <badlogicgames@gmail.com>
* Copyright 2013 Nathan Sweet <nathan.sweet@gmail.com>
/*
* Copyright 2014 Hannes Janetzek
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* This file is part of the OpenScienceMap project (http://www.opensciencemap.org).
*
* http://www.apache.org/licenses/LICENSE-2.0
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later version.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
* This program 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.oscim.utils.async;
/**
* Task to be submitted to an {@link AsyncExecutor}, returning a result of type
* T.
*
* @author badlogic
*
*/
public interface AsyncTask<T> extends Runnable {
public boolean cancel();
public abstract class AsyncTask extends Task {
private TaskQueue mainloop;
void setTaskQueue(TaskQueue mainloop) {
this.mainloop = mainloop;
}
/**
* Do not override! Unless you have a reason, of course.
*/
@Override
public void run() {
if (state == GO) {
/* running on worker thread */
state = go(false);
if (state == GO)
/* run on worker again */
mainloop.addTask(this);
else
mainloop.post(this);
} else {
/* post result on main-loop */
onPostExecute(state);
}
}
/**
* Executed on worker thread.
*
* @return Task.DONE on success, Task.ERROR otherwise
*/
public abstract int go(boolean canceled);
/**
* Executed on mainloop thread.
*/
public abstract void onPostExecute(int state);
public T getResult() throws Exception;
}

View File

@ -14,26 +14,30 @@
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.oscim.core;
package org.oscim.utils.async;
public abstract class Task implements Runnable {
public static final int ERROR = -1;
public static final int CANCEL = 0;
public static final int GO = 1;
public static final int DONE = 2;
protected int state = GO;
boolean isCanceled;
@Override
public void run() {
run(isCanceled);
go(state == CANCEL);
}
public void run(boolean canceled) {
}
/**
* @return ignored
*/
public abstract int go(boolean canceled);
public void cancel() {
isCanceled = true;
}
public void reset() {
isCanceled = false;
state = CANCEL;
}
}

View File

@ -0,0 +1,30 @@
/*
* Copyright 2014 Hannes Janetzek
*
* This file is part of the OpenScienceMap project (http://www.opensciencemap.org).
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.oscim.utils.async;
public interface TaskQueue {
/**
* Add task to run on a main thread.
*/
boolean post(Runnable task);
/**
* Add task to run on a worker thread.
*/
void addTask(Runnable task);
}