Probably the most important APIs of Android suited for Multithreading and offloading the tasks to worker threads- Handlers and Loopers.
The Android architecture has the Main Thread AKA UI thread, which updates the UI after every 16ms frame. Failure to update within this window will reflect as the “lag”, and even worse if it fails for 5secs, then the “Application not responding” shown to the user- marking the app crash. To avoid these types of issues, please resort to offloading the heavy tasks to worker threads.
To explain: the Android architecture has one main/UI thread which should ideally only be responsible for updating the UI, and other tasks should be done on separate threads(called worker threads). These worker threads upon completion should send the result back to the main thread and the main thread can then use it to update the UI, etc.
There are some Android APIs to do so like Async tasks, Services(Intent services actually), Executors, etc, etc.
But there are even cooler APIs available and are the core of all the above-mentioned APIs- Handlers and Loopers. …
Let's understand the different methods a Server can handle load/connections:
Let's say we have a simple Server, which inverts the case and returns back the changed output.
To test this server, telnet into this port and write any input. You will receive the Output with the inverted case:
telnet localhost 8080
Would also suggest going through the Handlers/Loopers working, and the basics of AsyncTasks at https://tinyurl.com/y4mbxa2w. The AsyncTasks are heavily using the ThreadPoolExecutors to do its tasks on the worker thread, and once done it passes back the result to the UI thread using Handlers.
Basic functions in Async are:
onPreExecute: Before the task begins
doInBackground: To do the task in background
onProgressUpdate: To update the progress of the task run
onPostExecute: After the task has run
But how do all these work together? How UI and worker threads communicate?
Let us start from the beginning:
Handlers are the Android Components used to communicate between the UI thread and the background threads.
The background thread(who has UI handler reference) can post messages to it, and the messages will be received in handleMessage() on the UI thread. …