Search code examples
streamingtwitter4j

how to stop and kill the Twitter4j stream correctly


I try to use the Twitter4j streaming features. So my implementation is in the following class :

public class TweetsStream {

    private TwitterStream m_twitterstream;
    private StatusListener m_statusListener;

    public void printStream(...)

        // Stream
        m_twitterstream = null;
        m_twitterstream = TwitterStreamFactory.getSingleton();

        // Listener
        m_statusListener = new StatusListenerRedefined(...);
        m_twitterstream.addListener(m_statusListener);

        // Filter
        FilterQuery l_filter = new FilterQuery();
        l_filter.track(... );

        // Launch
        m_twitterstream.filter(l_filter);
    }

    public void stopStream(){

        m_twitterstream.shutdown();
        m_logger.info("shutdown done");

        m_twitterstream = null;
        m_statusListener = null;
    }
}

My new StatusListener() prints the status in the console.

Then I create a TweetsStream object in another servlet class :

@WebServlet("/Controler")
public class Controler extends HttpServlet {

    private static final long serialVersionUID = 1L;

    // Logger
    protected final static Logger m_logger = Logger.getLogger("Controler");

    //Stream    
    private TweetsStream m_tweetStream;



    //Function...
    m_tweetStream = new TweetsStream(...);
    m_tweetStream.printStream(...);

}

The stream works perfectly. So i try now to stop it. In the same class I have the function :

private void stopStream(){
 m_tweetStream.stopStream();
 m_tweetStream = null;
}

The stream is stopped in the console, all is fine.

BUT When I recall in the same class my function :

    //Function...
    m_tweetStream = new TweetsStream(...);
    m_tweetStream.printStream(...);

It is as if i've just resume the previous m_twitterstream with one listener added. So I have two print of each tweet...

How to kill completely the Stream ? And when I relaunch it, how only have the last StatusListener ?

Thanks !


Solution

  • Here's the solution :

    The method TwitterStreamFactory.getSingleton() returns the same instance of the TwitterStream.

    Even if you delete properly your TwitterStream object, the listeners are stored in your TwitterStream Singleton config... So you have to create differents instances of the TwitterStream object with :

    TwitterStreamFactory l_Twitterfactory = new TwitterStreamFactory();
    m_twitterstream = l_Twitterfactory.getInstance();