Home > Mobile >  What is the cleanest way to create, start, and manage long-running threads?
What is the cleanest way to create, start, and manage long-running threads?

Time:01-12

Threads add a lot of verbal to the code and make it harder to understand and reason about. Look at this code for example:

public class ConnectionListener implements Runnable {
            
    private Thread thread;
    private boolean running;
    
    public void start() {
        if (!running) {
            thread = new Thread(this);
            thread.start();
        }
    }
    
    public void stop() {
        if (running) {
            running = false;
            thread.interrupt();
        }
    }
    
    @Override
    public void run() {
        running = true;
        
        while (running) {
            // Do some crap
        }
    }
    
}

The whole concern of this class should be listening for connection requests from the network. But look how many lines of code are added just for managing a thread. Is there any way to make this code cleaner?! I don't want to see the thread = new Thread();, not the thread variable and not any of the stop()/start() methods!

Of course I know what the ExecutorService is... But what if I want to manage a long-running thread? By long-running thread, I mean a thread with a life cycle long as the application's life cycle.

Do you have any good solution for me? A way to remove the thread creation and management concerns from a class without making the class extend another class?

CodePudding user response:

I solved the problem by using a single-threaded executor service. I've also read about the performance differences between Plain Thread, ThreadPool and SingleThreadExecutor - SingleThreadExecutor VS plain thread.

Using a single thread executor allows me to start a single thread and manage it using its Future. See code example:

public void func(String[] args) {
   ExecutorService es = Executors.newSingleThreadExecutor();
   Future<?> f = es.submit(Some Runnable);
}

Thanks to @BasilBourque that gave me this solution in the comments.

  •  Tags:  
  • Related