Reading this guide on how to analyze images fed directly from the camera; in the code example on the bottom of the page there suddenly pops up a new variable executor:
imageAnalysis.setAnalyzer(executor, ImageAnalysis.Analyzer { imageProxy ->
Looked it up, an Executor is just another parallelization abstraction. Now, how do I get one? Is there something like this?
androidThreadPool.getExecutor()
Actually, I found one:
Context.getMainExecutor()
If I understand this correctly, this would execute the Runnable on the main thread. However, I assume the point of providing an Executor to the ImageAnalyzer is to not run it on the main thread.
Or do I have to create my own Executor? Is this common practice to do so?
No, not “just another”. The Executors framework was a major milestone in the evolution of Java. This framework relieved the burden of managing threads from the shoulders of Java programmers, making concurrency work much simpler.
ExecutorService, notExecutorThe
Executorinterface is not the most commonly used part. That interface defines theexecutemethod which may run your task on a background thread or may just as well run the task on the current thread.If you know you want a background thread, use an implementation of the
ExecutorServicesub-interface with its methods likesubmit.Usually, we obtain an unspecified implementation of
ExecutorServiceby calling a convenient factory method on theExecutorsclass.You may want an executor service backed by a pool of any number of threads. Use this only when you know you a limited number of simultaneous tasks, so as to not overburden your machine.
You may want an executor service backed by a pool of a certain number threads.
In modern Java, versions 21+, we use virtual threads for most purposes. I assume Android does not offer virtual threads, and won’t any time soon.
Any of these executor services can run your tasks you define as either a
Runnableor aCallable.No, that would be a very rare situation where you would need a custom executor service.
No.
The purpose of the Executors framework is to avoid dealing with the low-level details of juggling threads and tasks. Several good implementations of
ExecutorServiceare bundled with Java, made available to you viaExecutorsclass.Caveat: I don’t know Android. My comments here apply to the Java platform. My comments may also apply to Android; I just don’t know.