I have a class MyTaskRunner
that uses Executor
to run Callable
tasks asynchronously, in this class there is an Handler
binded to mainLooper e.g
public class MyTaskRunner {
private final Handler handler = new Handler(Looper.getMainLooper());
private final Executor executor;
MyTaskRunner{
this.executor = Executors.newCachedThreadPool();
}
public <R> void executeAsync(MyCallable<R> callable) {
try {
callable.setUiForLoading();
executor.execute(new RunnableTask<R>(handler, callable));
} catch (Exception e) {
}
}
public static class RunnableTask<R> implements Runnable{
private final Handler handler;
private final MyCallable<R> callable;
public RunnableTask(Handler handler, MyCallable<R> callable) {
this.handler = handler;
this.callable = callable;
}
@Override
public void run() {
try {
final R result = callable.call();
handler.post(new RunnableTaskForHandler(callable, result));
} catch (Exception e) {
}
}
}
public static class RunnableTaskForHandler<R> implements Runnable{
private MyCallable<R> callable;
private R result;
public RunnableTaskForHandler(MyCallable<R> callable, R result) {
this.callable = callable;
this.result = result;
}
@Override
public void run() {
callable.setDataAfterLoading(result);
}
}
}
should I use a single
private static final Handler handler = new Handler(Looper.getMainLooper());
or
create a new instance of it for each new MyTaskRunner
e.g. using this constructor
MyTaskRunner (){
this.handler = new Handler(Looper.getMainLooper());
this.executor = Executors.newCachedThreadPool();
}
using a single static Handler
uses less memory in case are used multiple MyTaskRunner
, but I'm not sure if this could cause unwanted interferences across multiple MyTaskRunner executed at same time
question from:
https://stackoverflow.com/questions/65851797/should-the-main-looper-handler-be-declared-as-static-or-reinstanced-each-time-fo 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…