Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tailer don’t stop

I have implement a tailerListener in my program but when I start it, it never stop.

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);
    }
}

At the beginning, I managed to go to the tailer.stop (so my program stopped, great) but after write some other lines and touch to several things, it did not work any more.

Strange thing, when I replace my class MyTailerListener by:

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 have just pick it out from an answer, but it does not concern my file. Then my program stop…

I think it is because of it can’t find the matcher.group(1). When I remove all the sysout but the first, my program does not stop.

like image 464
Chènevis Avatar asked Apr 13 '26 14:04

Chènevis


1 Answers

The way you implemented the Executor, the tailer gets run in the same thread. What you probably want to do is create a new thread to execute MyTailerListener in. Try eg.

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

Note however, that use of Thread.stop() is generally discouraged because it does not allow threads to terminate cleanly. Also, in this particular example the thread might be terminated 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 tailer (eg. Thread.sleep(1000);), but you should really define when (under which conditions) the program should be stopped and implement that cleanly instead.

like image 119
emu Avatar answered Apr 16 '26 03:04

emu



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!