Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does a program run after main() exits?

I have written a program that uses the twitter stream to write tweets in Realtime to a File via a BufferedWriter. But the bufferedWriter does not write the text until i call the close() method at the end of the main function.

Now, when i run the program, the file is closed at first and then the tweets start coming. How does this thing work after main exits???

Here is the Code:

package analytics;


import twitter4j.*;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;

public final class Trial_Filters {

static String Tweet;
static FileWriter output;
static BufferedWriter writer;



public static void main(String[] args) throws TwitterException,IOException {



    if (args.length < 1) {
        System.out.println("Usage: java twitter4j.examples.PrintFilterStream [follow(comma separated numerical user ids)] [track(comma separated filter terms)]");
        System.exit(-1);
    }


    output= new FileWriter("Log.txt");
    writer=new BufferedWriter(output);




    StatusListener listener = new StatusListener() {
        public void onStatus(Status status) {
            StringBuilder temp;


            //System.out.print("<sta>"); // Start Status -- helps for parsing two lines tweet;<sta> and </sta> used as tweet delimiters
            temp=new StringBuilder("<sta>");

            if(status.isRetweet())
                temp.append("%");//System.out.print("%"); // easier to identify ReTweets

            //System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText());
            temp.append("@" + status.getUser().getScreenName() + " - " + status.getText());

            //System.out.print("</sta>");   //End Status
            temp.append("</sta>");

            Tweet=temp.toString();

            this.add_to_Log();

        }


        private void add_to_Log(){
            // TODO Auto-generated method stub
            try{
            output= new FileWriter("Log.txt");
            writer=new BufferedWriter(output);

            writer.write(Tweet);
            System.out.println(Tweet);
            }
            catch(Exception e)
            {
                System.out.println(e);
            }

        }


        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
            System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
        }

        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
            System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);
        }

        public void onScrubGeo(long userId, long upToStatusId) {
            System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
        }

        public void onException(Exception ex) {
            ex.printStackTrace();
        }
    };

    TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
    twitterStream.addListener(listener);
    ArrayList<Long> follow = new ArrayList<Long>();
    ArrayList<String> track = new ArrayList<String>();
    for (String arg : args) {
        if (isNumericalArgument(arg)) {
            for (String id : arg.split(",")) {
                follow.add(Long.parseLong(id));
            }
        } else {
            track.addAll(Arrays.asList(arg.split(",")));
        }
    }
    long[] followArray = new long[follow.size()];
    for (int i = 0; i < follow.size(); i++) {
        followArray[i] = follow.get(i);
    }
    String[] trackArray = track.toArray(new String[track.size()]);

    // filter() method internally creates a thread which manipulates TwitterStream and calls these adequate listener methods continuously.
    twitterStream.filter(new FilterQuery(0, followArray, trackArray));


    try{
        System.out.println("bye");
         writer.close();
        }
        catch(Exception e)
        {
            System.out.println(e);
        }


    }


private static boolean isNumericalArgument(String argument) {
    String args[] = argument.split(",");
    boolean isNumericalArgument = true;
    for (String arg : args) {
        try {
            Integer.parseInt(arg);
        } catch (NumberFormatException nfe) {
            isNumericalArgument = false;
            break;
        }
    }
    return isNumericalArgument;
}

}

like image 752
nikel Avatar asked May 19 '26 20:05

nikel


2 Answers

The virtual machine terminates all activity and exits after the last non-daemon thread ("User Thread") has terminated (or some thread invoked System.exit()). That last User thread doesn't have to be the main thread.

The tweets (packets) are sent to a local socket and the socket is only bound as long as the virtual machine is up and running (in case the socket hasn't been closed manually). So the feed may be sending but the computer won't accept the data and the tweet source will receive errors.

like image 115
Andreas Dolk Avatar answered May 21 '26 09:05

Andreas Dolk


The TwitterStream Object will start a thread, and that thread will call back on the StatusListener. The program will run until there is a thread running, even if the main thread seems to have finished, it waits for all other threads to stop, before the main thread stops, and the program exits.

It does not matter if you close the writer or not on the end of main. The reference of the writer will be rewritten on each call to add_to_log. That means on each new status a new writer gets instantiated, writes out the message into the bufferedwriter.

The following two lines at the beginning of the code are irrelevant:

output= new FileWriter("Log.txt");
writer=new BufferedWriter(output);

However it would be better to call flush() or close() in add_to_log to make sure everything gets written to disk.

like image 23
reegnz Avatar answered May 21 '26 09:05

reegnz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!