The following SSCCE does exactly what you want and are expecting:
public class App
{
public static void main(String[] args) throws FileNotFoundException, InterruptedException, ExecutionException
{
PrintStream oldErr = System.err;
System.setErr(new PrintStream(new File("test")));
ExecutorService threadPool = Executors.newFixedThreadPool(5);
List<Future<?>> fList = new LinkedList<Future<?>>();
for (int i = 0; i < 5; i++)
{
fList.add(threadPool.submit(new Runnable() {
@Override
public void run()
{
System.err.println("This is to the err stream");
}
}));
}
for (Future<?> f : fList)
{
f.get();
}
threadPool.shutdown();
System.setErr(oldErr);
System.err.println("This is to the err stream");
}
}
After running this example, the file "test" contains 5 lines, each saying "This is to the err stream" and at the end one additional line is printed to the console.
The code snippet you show is calling System.setErr(oldErr);
in the finally
block ... have you waited for all your tasks to complete in that try
block?
If not it would explain the statement you make in the comments that "I would see fragments of output printed to System.err and fragments printed to my logfile" ... that's pretty much what you'd expect to happen. .submit()
is a non-blocking call that returns a Future
; you're resetting the stream while your tasks are running.