Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Keep Listener Thread Alive

I have a class which is a listener for incoming messages and should be alive forever (So that it can listen for incoming messages) until i explicitly disconnect the connection for it. I have declared the thread as setDaemon(false) but it terminates with the calling methods termination.

Please tell me how to keep that thread alive and also please throw some light on how to implement the Spring TaskExecutor to achieve same.

Thanks in advance. it is a listener it gets notified when someone sends message... so how do i keep it running ?

The Listener Class

public class MyListnerImpl implements Listener {
    private final connectionImpl con;   

    public MyListnerImpl(ConnectionImpl con) {
    if (con.isAuthenticated() && con.isConnected()) {
        if (logger.isInfoEnabled()) {
            logger.info("Initializing XmppListner:");
        }
        this.itsCon = con;
        Thread t1 = new Thread(this);
        t1.setDaemon(false);
        t1.start();
    }
    }

    public final void listnerInterfaceMethod(final Chat chat, final Message message) {
        System.out.println("Message" + message);
    }

    public final void run() {
    itsCon.getChatManager().addChatListener(new ChatManagerListener() {
        public void chatCreated(final Chat chat, final boolean createdLocally) {
            if (!createdLocally) {
                chat.addMessageListener(itsFbml);
            }
        }
    });
    }
}

Calling class simply creates its object and thread gets started by the Listeners constructor.

I want to keep this thread created run until i interrupt it.

like image 792
Alind Billore Avatar asked Oct 22 '13 15:10

Alind Billore


2 Answers

There are a few things you could do that would be better than hanging the initial thread forever:

Use otherThread.join(). This will cause the current thread you are running in to sleep until the other thread has finished executing. As @nanda suggests, use ExcecutorService.shutdown() to wait until a pool of threads has finished. Use otherThread.setDaemon(false) and simply let your initial thread exit. This will set your new threads as user threads. Java will not shut down until the only threads running are daemon threads.

synchronized(this) {
    while (true) {
        this.wait();
    }
}

This will make the current thread wait on the monitor of the current class until someone calls notify(), or forever.

copied from How do you hang a thread in Java in one line?

like image 99
SSP Avatar answered Nov 19 '22 02:11

SSP


A thread says alive until run() returns (or throw an error/exception) If you want to keep it alive, use a loop, don't return and catch any error/exception.

like image 34
Peter Lawrey Avatar answered Nov 19 '22 02:11

Peter Lawrey