3

I am writing java program that creates different instances of Runnable objects given by someone and then runs them. For instance user gives me a .class file with runnable class and I create instance of that object and run it. Everything works fine until I decided to monitor every different thread's progress. Lets say that current Runnable object print all the numbers from 1 to 9 in console. I want to catch that output and return it as a String. Using System.setOut(..) prevents me from using console, so it is not an option.

1 Answer 1

3

Using setOut doesn't prevent you from using the console, if you save it first and it is your only option unless you use byte code instrumentation.

static final PrintStream OUT = System.out;
static {
   // capture all System.out
   System.setOut(new MyPrintStream());

   OUT.println("Print as normal");
}

class MyPrintStream extends PrintStream {
    final ThreadLocal<StringBuilder> text = ThreadLocal.withInitial(() _> new StringBuilder());

    public void print(String s) {
       StringBuilder sb = text.get();
       sb.append(s);
    }

    public void println(String s) {
       StringBuilder sb = text.get();
       sb.append(s).append('\n');
       // do something with sb.
    }
Sign up to request clarification or add additional context in comments.

3 Comments

Aw, that's pretty neat solution to my problem, I had not think of. Thank you :)
@miroslavlalev I have added how you can use a ThreadLocal to collect the output of each thread.
I tried to upvote you before I write my comment but I need 15 reputation :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.