Updated to be more graceful with error handling in Java and to handle multithreading environments better