Search code examples
androidmultithreadingandroid-asynctaskworker-thread

Creating threads from inside a worker thread in Android


In my app, I need to make a number of TCP socket calls.

To be able to do this, I have to do the following steps: 1. convert my data/command into a byte stream 2. create socket and send command and receive response 3. parse response and store for UI to use.

Now I have created a background thread to be able to do all three steps.

But in my socket client also I want to create a new thread for each new command (Step# 2) So that would mean that I have a number of worker threads inside the common worker thread for all the three above steps.

So, would it be ok to use Async task for step #2 which is already taking place in a worker thread. Or do I use normal thread in this case.

One might wonder why am i not achieving all three steps in one worker thread. The point is that even if I create just one worker thread for all the socket commands, there is a possibility that the initial request for step 1 might itself come from a worker thread.

Hence, I cannot just assume that the call is from Main UI thread. Also, I wanted to ask whether it is not recommended to create your own worker threads in android and why?

Thanks, Sunny


Solution

  • Form your first 2 paragraphs i understand you want to establish some communication via sockets. i dont believe it would be a good approach to create a thread per command as thread itself and opening/closing sockets are expensive operations. i would suggest creating only one thread for opening and monitoring/writing/reading data to/from socket. if these commands are frequent than maintaining one socket alive is more appropriate than frequently opening/closing sockets. optionally i would create an extra thread for doing the extra work of serializing/deserializing commands (if they r time-consuming).

    One might wonder why am i not achieving all three steps in one worker thread. The point is that even if I create just one worker thread for all the socket commands, there is a possibility that the initial request for step 1 might itself come from a worker thread.

    I dont think it would make a big difference in your design approach where the requests come from.

    Hence, I cannot just assume that the call is from Main UI thread. Also, I wanted to ask whether it is not recommended to create your own worker threads in android and why?

    Android provides some very good generic classes such as AsyncTask and HandlerThread for general purpose usages but anyone is free to create a worker thread if the above ones do not fit the design requirements. Personally i create my own worker threads if i deal with socket programming.

    I would suggest taking a look at Java NIO library specifically Selectors, and SocketChannel classes