Database Reference
In-Depth Information
When tacking code on like this, it is good to remember the context and the synchronization demands. If
this were a method that is being called by a multithreaded server application, then we would need to
assure that only one user at a time will be opening, writing
and closing the file. One way to accomplish
that would be to declare the method to be
synchronized
(add the
synchronized
keyword to the method
signature, before the return type declaration). Another way that doesn't involve changing the existing
method signature is to
synchronize
on an object. It can be any type of object, but it should be a static class
member so that everyone is synchronizing on the same thing.
Often you will attempt to synchronize the smallest section of code that you can, and in that case you might
synchronize each
debugOut.println()
statement. But in that case you might also need to declare your
debugOut
PrintStream
as a static class member. However to add synchronization to our spot debugging,
we will synchronize a larger section and allow each request of the
methodName()
method to have
exclusive access to the debug.txt file from open to close. It will look like this:
static String synchOnThis = “”;
returnType methodName() throws Exception {
try {
PrintStream debugOut = null;
synchronized( synchOnThis ) {
try {
debugOut = new PrintStream ( new FileOutputStream( “debug.txt” ) );
while() {
debugOut.println( “message 1” );
if() {
debugOut.println( “message 2” );
}
debugOut.println( “message 3” );
}
debugOut.println( “message 4” );
} finally {
if( debugOut != null ) {
debugOut.flush();
debugOut.close();
}
} }
for() {
}
catch( Exception x ) {
} finally {
}
}