简体   繁体   中英

Detect closing stream of twitter4j

I'm Developping an application using twitter4j. I store the tweets in a file using a DAO.

I made an implementation of the StatusListener class :

public class StatusListenerStore implements StatusListener {

    // DAO
    private DAO<Status> m_statusDAO;


    // Constructor
    public StatusListenerStore(FactoryType a_factoryType,ArrayList<String> a_lanTrackList) {

        super();
        AbstractDAOFactory l_DAOFactory = AbstractDAOFactory.getFactory(a_factoryType);
        m_statusDAO = l_DAOFactory.getTweetDAO();

    }
}

The DAO called is :

// Extract of my class
private static HadoopFileSystem m_hadoopFileSystem = null;

public TweetHADOOPDAO(){
    m_hadoopFileSystem = new HadoopFileSystem(m_path+m_filename);
}

public void close(){
    m_hadoopFileSystem.closeWriters();
}

The HadoopFileSystem contains OutputStream i have to close.

First of all, I want only ONE HadoopFileSystem object instance for all my program. The static keyword guarantees me ?

Next, to close my outputstream, i have to call the close function in my DAO class when the stream is done. I close it using the correct shutdown() function.

But the m_statusDAO object is declared in my StatusListener class. How can i call my close() function in this class when the stream is close ?

The static keyword means that the m_hadoopFileSystem variable will be shared by all instances of the class, however it does not prevent you from assigning the variable multiple times. Currently you will get a new HadoopFileSystem each time you instantiate an TweetHADOOPDAO object, overwriting the reference to any existing HadoopFileSystem objects.

If you truly need to ensure only one instance is created, take a look at using the singleton pattern .

On your second point, unfortunately I don't think there is a shutdown event. However, you could add a shutdown() method to your listener which invokes TweetHADOOPDAO#close() .

Then you could additionally call StatusListenerStore#shutdown() after you invoke TwitterSteam#shutdown() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM