Efficient way to handle/manage around hundreds of threads in Android

android thread tutorial
android multithreading best practices
android thread example
threads in android tutorial point
android background thread example
android ui thread
how to start and stop thread in android
types of thread in android

We're developing this app that can send commands to smart devices. The smart device connects to the app using ServerSocket. When a device connected, the app will create 2 threads (For sending command and for receiving the response). So if there are 50 devices connected, the app will create 100 threads.

What happens is that if around 60 devices are already connected, their threads are getting killed by the android. There are also instances that when the device disconnects, the app is not able to detect it.

We would like to connect maximum of 200 devices to the app.

So my questions:

  1. Is this the correct way or method for this kind of task?
  2. How to properly know how much threads the android device can use?
  3. What's the efficient way to handle these threads?

Any tips on the right direction is greatly appreciated. Thank you

The following are the codes:

ConnectionThread.class

public class ConnectionThread extends Thread {
  private ServerSocket serverSocket;

  @Override
  public void run() {
    Socket socket;
    try {
      serverSocket = new ServerSocket(PORT);
      listener.onStartedListening();
    } catch (IOException e) {
      e.printStackTrace();
    }
    while (!Thread.currentThread().isInterrupted()) {
      try{
        socket = serverSocket.accept();
        ReceiveThread receiveThread = new ReceiveThread();
        receiveThread.start();
        SendThread sendThrd = new SendThread();
        sendThrd.start();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
}

The ReceiveThread and SendThread both extends Thread. They handle the sending of command and receiving response from the device.

From my experience with sockets, you can put both of the IO streams on the same thread, so that should at least cut down on the number of threads. As for the disconnect issue, you should have the server send periodic pings and set a timeout interval for responses, after which the connection should be terminated.

Better performance through threading, Android provides many ways of creating and managing threads, and Every Android developer, at one point or another, needs to deal with threads in their application. When an This, in my opinion, would be the best option. But as you have noticed, it involves some work, and too many broadcasts can slow things down. Android provides many ways to handle and manage threads, but none of them are silver bullets. Choosing the right threading approach, depending on your use case, can make all the difference in making the overall solution easy to implement and understand.

My Suggestion would be to use NanoHTTP https://github.com/NanoHttpd/nanohttpd This wheel is already implemented i would request you to modify according to your needs. I have used and it also supports https.

Android Threading: All You Need to Know, Every Android developer, at one point or another, needs to deal with threads in their application. Android provides many ways of creating and managing threads, and there are ThreadPoolExecutor: Running lots of parallel work AsyncTask is designed to be a helper class around Thread and Handler  Alternatively, if you don't want to manage the details of the thread pool sizing, you may find the Executors factory methods for creating a single thread executor or the work stealing executor more convenient. More information. To learn more about multi-threaded operations on Android, see the Process and threads overview guide. Sample app

You don't. That is why non-blocking IO has been invented and implemented in Java in the form of a Selector since 2002.

The core problem with Threads is that at some point just switching between threads costs more time than the threads itself could ever safe. The most simple solution is to only have a single thread that takes all the requests and decides whether or not to forward them to worker threads. This singular thread can answer all requests that take faster to answer than to spawn a thread on it's own (like echo requests), and let the heavy weight work be done back background threads, that are limited by the amount of cores. So at top you'd have to manage cores * 2 threads in this scenario.

As this is very old technology, there are many libraries available that do this for you already. As mentioned in another answer: reinventing the wheel is not necessary here.

Threading in Android - Better Programming, All the Android UI toolkit components will run in the main process and are handled (managed) inside the UI thread. For this reason, methods that respond to  Understand multithreading basics in Java and on the Android platform Learn how threads communicate within and between processes Use strategies to reduce the risk of memory leaks Manage the lifecycle of a basic thread Run tasks sequentially in the background with HandlerThread; Use Java’s Executor Framework to control or cancel threads

Android Apps for Absolute Beginners, First definition of Handler: It is the Android way of Thread communication. It is not Best way to understand something is make our own hands dirty. Android framework devised this mechanism of passing messages around and used it like no tomorrow. Handler is the place where you handle messages and take action. ThreadPoolExecutor is a great way to execute parallelized tasks across multiple different threads within a limited thread pool. If you want to execute work concurrently and retain control over how the work is executed, this is the tool for the job.

Mastering Android Handler - MindOrks, There is a tendency to just use Java threads or Android AsyncTasks for This means that they are not the best option for long running operations and also, Android HandlerThread, can be used to handle messages of a background thread. Can we run 4 thread parallel i.e. at the same time in Android ?? Yes, you can run 4 thread in parallel. Adding more threads usually helps, but at some point, they cause some performance degradation. But 4 threads will not cause an issue. Issues: I am not able to run thread parallel i.e. 1st Threads runs : 4 times, 2nd 3rd n 4th only 1 time.

8 ways to do asynchronous processing in Android and counting, Binder Threads An Android remote process is just a different process. All of the Methods on a Service managed object in the remote process, however, are called from Binder threads. A Binder There is a way around this, though. Because  Managing Threads in Android ™ Application developers have built containers to house threads since the advent of modern computing because controlling a thread of execution, even within a Service, is a potential nightmare. This article expounds Open Source Tymeac™, a Service container for managing Android™ application threads. (2000 words)

Comments
  • You can't combine the two threads into a single thread that handles both functions?
  • use thread pool