Redirect System.err for a single thread
Is it possible to redirect System.err for a single thread?
I have a servlet that kicks off javac. I save the System.err PrintStream and I redirect System.err to an output file during the compile. After the compile is complete, I redirect System.err back to it's original destination and read the file if the compile did not complete successfully.
Unfortunately, I believe there is a small hole here if another thread wants to write to System.err during the time a compile is taking place and I may end up with these messages in my compile output file. What I would really like to do is only redirect System.err for the thread that the compile is taking place on. Does anyone know if this is possible? Thanks.
[735 byte] By [
jburggraf] at [2007-9-26 1:17:56]

as to your original question, i don't think that is possible because, there is "only one" stderr for a system and if you redirect that, you are effecting the whole system. so your redirection target becomes the system wide stderr
You can achieve this by turning the problem around. Write an output stream that redirects depending on the current thread:
public class ThreadPrintStream extends PrintStream
{
private PrintStream out1;
private PrintStream out2;
private Thread redirectThread;
public ThreadPrintStream(PrintStream out1, PrintStream out2, Thread redirectThread)
{
this.out1 = out1;
this.out2 = out2;
this.redirectThread = redirectThread;
}
public void print(String s)
{
if(Thread.currentThread() == redirectThread)
{
out2.print(s);
}
else
{
out1.print(s);
}
}
// etc.
}
You would then do something like:
System.err = new ThreadPrintStream(System.err, myPrintStream, myThread);
Hope this helps.