Tailer doesn't stop

I am using tailerListener in my program, but when I run it, it never stops.

Here is my program:

public class PostClient{

private static File file = new File("../file.txt");

public static void main(String [] args){    

//      TAILER LISTENER
    TailerListenerAdapter listener = new MyTailerListener();
    Tailer tailer = new Tailer(file, listener, 500);

    Executor executor = new Executor() {
          public void execute(Runnable command) {
              command.run();
           }
    };

    System.out.println("Execution of the tailer");
    executor.execute(tailer);
    System.out.println("Stop tailer");
    tailer.stop(); 

      

with my class MyTailerListener

import org.apache.commons.io.input.TailerListenerAdapter;

public class MyTailerListener extends TailerListenerAdapter {
    public void handle(String line) {
        System.out.println(line);
    }
}

      

In the beginning, I managed to navigate to tailer.stop (so my program stopped, great), but after writing some other lines and touching a few things, it didn't work anymore.

Weird thing is when I replace my MyTailerListener class with:

public void handle(String line) {
    final String logEntryPattern = "(\\w+\\s+\\d+\\s+\\d{2}:\\d{2}:\\d{2})\\s+(\\S+)\\s+(\\S+):\\s+(.+)";
    final Pattern p = Pattern.compile(logEntryPattern);
    final Matcher matcher = p.matcher(line);

System.out.println("Total groups: " + matcher.groupCount());
System.out.println("Date&Time: " + matcher.group(1));
System.out.println("Hostname: " + matcher.group(2));
System.out.println("Program Name: " + matcher.group(3));
System.out.println("Log: " + matcher.group(4));
}

      

I just picked this from the answer, but it doesn't apply to my file. Then my program stops ...

I think it cannot find matcher.group (1) because of this. When I delete all sysout but the first one, my program doesn't stop.

+3


source to share


1 answer


As you have implemented Executor, the tailer runs on the same thread. You might want to create a new thread to run the MyTailerListener. Try for example.

Thread tailerThread=new Thread(tailer);
tailerThread.start();
System.out.println("Stop tailer");
tailerThread.stop();

      



Note, however, that using Thread.stop () is usually discouraged because it prevents threads from completing cleanly. Also, in this particular example, the thread can be interrupted before it does any work at all. You probably don't want that. Another quick hack would be to wait a second before stopping the tailor (e.g. Thread.sleep (1000);), but you have to actually determine when (under what conditions) the program should be stopped and implement it cleanly.

+2


source







All Articles