10

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.

Thanga
  • 7,811
  • 3
  • 19
  • 38
Alind Billore
  • 696
  • 2
  • 10
  • 24
  • can you post your code? – Rajj Oct 22 '13 at 16:02
  • possible duplicate of [How do you hang a thread in Java in one line?](http://stackoverflow.com/questions/3203139/how-do-you-hang-a-thread-in-java-in-one-line) – SSP Oct 22 '13 at 16:05
  • I have posted the thread, gentleman please tell me what you guys usually do to keep listener running ? – Alind Billore Oct 22 '13 at 16:18
  • 1
    I would think that the listener should stay registered forever unless the `ChatManager` is removing the listener for some reason. You should not need to do the register in a background thread and there is no reason to keep that thread running. As Peter points out, your listener code will be called from a different thread. – Gray Oct 22 '13 at 20:12
  • I don't know what you are trying to do, but the thread here is useless, as others said you can get rid of it and seek your problem elsewhere. – Flavio Oct 22 '13 at 20:26
  • Ok Gray so listener calls from somewhere else. @Flavio Try to understand, this piece of code is not useless, it gets notified in case of any event... the question is simple,it must be alive to listen to that notification, but this code also terminates with main method. if any of you wise people can help me to do that, i would be greatfull. How can we instantiate a listener so that i keeps listening for events ?? – Alind Billore Oct 22 '13 at 20:38
  • I did not say the code is useless; I'm saying that it is useless to run it into a separate thread. You can run the code in the main thread, you don't need another thread here. Just put a `while(true) sleep(1000);` in your main thread, if that's your problem. – Flavio Oct 22 '13 at 20:55

3 Answers3

3

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?

Community
  • 1
  • 1
SSP
  • 2,650
  • 5
  • 31
  • 49
1

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.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • Hello peter, it is a listener it gets notified when someone sends message... so how do i keep it running ? I have declared it as non daemon thread but terminates with caller threads termination. How do you implement such kind of thing ? – Alind Billore Oct 22 '13 at 16:20
  • It is not clear if you control the thread or not. Whether it is a deamon or not only matters in preventing the program from exiting. If you control the thread, you need to change your code. If the thread is created by a library, you need to understand how the library works. – Peter Lawrey Oct 22 '13 at 16:26
  • BTW The thread you started doesn't appear to do anything. You could remove it and it will do the same thing. It is not the thread the listener will can called on. – Peter Lawrey Oct 22 '13 at 16:28
  • thanks for replying peter, This code basically gets notified when a message arrives... So this must alive when some one looks for it... So how to keep it alive any suggestion ? – Alind Billore Oct 22 '13 at 20:42
0

This is how i solved the problems that time, So this case was not of multi threading , had just a single thread which needed to run for ever, So Inserted

public final void run() {
while(true)
{
//Run Method Logic...
}
}

And instantiated it from a spring bean. I was also looking at more fancy things for this single threaded scenario like awaitTermination(); or something like that.

Alind Billore
  • 696
  • 2
  • 10
  • 24