This is an abbreviated version of a serial receiver that can be started and stopped like a resource. The idea is that a thread will listen to an InputStream and dispatch received data to registered listeners. Effectively this converts a pull-style InputStream to push-style CommunicationListener (own interface). While it works perfectly for my purposes (closing the receiver stops the thread and cleans up resources), I think it's bad practice that the receiver can't close itself. I wonder if I have the wrong approach here.

Ignore the lack of thread-safety/@Nullable/etc in this example, it's all present in the production version.

public class TempReceiver {
    public static void main(String... args) {
        TempReceiver receiver = new TempReceiver();

    private InternalThread receiveThread = new InternalThread();

    public void open() {

    public void close() { // blocking call
        receiveThread.join(1000); // Why no exception when self-joining?

        if (receiveThread.isAlive())
            throw new RuntimeException("Timeout while stopping thread"); // printed

        receiveThread = null; // clean up resources

    class InternalThread extends Thread {
        public void run() {
            try {
                System.out.println("Receiver busy");

                // Invoke listener here with received data.
                // Some listener decides that the receiver can be closed.
            } catch (InterruptedException e) { }


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.