by BehindJava

How to parse logs written by multiple Threads

Home » java » How to parse logs written by multiple Threads

This is a quick tutorial on parsing logs written by multiple Threads.

It sounds like there are some existing parser classes already in use that you wish to leverage. In this scenario, I would write a decorator for the parser which strips out lines not associated with the process you are monitoring.

It sounds like your classes might look like this:

abstract class Parser {
    public abstract void parse( ... );
    protected String readLine() { ... }

class SpecialPurposeParser extends Parser {
    public void parse( ... ) { 
        // ... special stuff
        // ... more stuff

And I would write something like:

class SingleProcessReadingDecorator extends Parser {
    private Parser parser;
    private String processId;
    public SingleProcessReadingDecorator( Parser parser, String processId ) {
        this.parser = parser;
        this.processId = processId;

    public void parse( ... ) { parser.parse( ... ); }

    public String readLine() {
        String text = super.readLine();
        if( /*text is for processId */ ) { 
            return text; 
        else {
            //keep readLine'ing until you find the next line and then return it
            return this.readLine();

Then any occurrence you want to modify would be used like this:

//old way
Parser parser = new SpecialPurposeParser();
//changes to
Parser parser = new SingleProcessReadingDecorator( new SpecialPurposeParser(), "process1234" );

This code snippet is simple and incomplete, but gives you the idea of how the decorator pattern could work here.