I am working through a school book example as on how to write data into a SQlite database using Room in Android. Apparently, we cannot write data into the database from the main-thread, but we need a background-thread for this. In my book, what we do is, we create an extra class AppExecutors
with the following content:
public class AppExecutors {
private final Executor _diskIO;
private final Executor _networkIO;
private final Executor _mainThread;
private AppExecutors(Executor diskIO, Executor networkIO, Executor mainThread) {
_diskIO = diskIO;
_networkIO = networkIO;
_mainThread = mainThread;
}
public AppExecutors() {
this(Executors.newSingleThreadExecutor(),
Executors.newFixedThreadPool(3),
new MainThreadExecutor());
}
public Executor diskIO() {
return _diskIO;
}
public Executor networkIO() {
return _networkIO;
}
public Executor mainThread() {
return _mainThread;
}
private static class MainThreadExecutor implements Executor {
private Handler mainThreadHandler = new Handler(Looper.getMainLooper());
@Override
public void execute(Runnable command) {
mainThreadHandler.post(command);
}
}
}
Then, inside the MainActivity, which contains the UI as well, i.e. the button, which triggers an action when clicked, we call
getApp().getExecutors().diskIO().execute(() -> {
...
}
where getApp().getExecutors()
returns a new instance of AppExecutors
.
Here is my question:
I do understand that getApp().getExecutors().mainThread().execute(() -> {...}
is passed a new Runnable and this Runnable is given to the messagequeue of the main-thread. The looper takes each thread out of the messagequeue and executes it.
However, things are different for getApp().getExecutors().diskIO().execute(() -> {...}
.
The Runnable that is passed to it is apparently executed in a background thread. Executors.newSingleThreadExecutor()
seems to be opening up a new thread. But there is no handler or messagequeue associated with this thread. So, I was wondering, won't this thread be closed after execution? Once the thread is closed, we cannot open the same thread again. And that's a bit confusing for me, shouldn't the thread stay open?
I have read up on the ExecutorService now and apparently this service just lets the thread stay open. But then again, isn't this the same thing that the messageque and the handler are doing? So how is this different?