> I want all the classes write the runtime information into one common
> file, let's say, log.
[quoted text clipped - 30 lines]
> looks like I cannot either catch it here or put the "throws
> IOException...." sentence after "public class Tester".
Try this:
public class Tester {
private static BufferedWriter logger;
public static BufferedWriter getLogger() throws IOException {
if (logger==null) {
logger = new BufferedWriter(whatever...);
}
return logger;
}
}
In your code, call:
Tester.getLogger().write("some message");
Of if you want to avoid the call to if (logger==null) on every log
statement, create a static init() method and call that before the first
call to getLogger().
xz - 06 Aug 2007 22:39 GMT
> > I want all the classes write the runtime information into one common
> > file, let's say, log.
[quoted text clipped - 52 lines]
> statement, create a static init() method and call that before the first
> call to getLogger().
Thanks. That works.
Lew - 06 Aug 2007 22:56 GMT
>> I want all the classes write the runtime information into one common
>> file, let's say, log.
[quoted text clipped - 51 lines]
> statement, create a static init() method and call that before the first
> call to getLogger().
The latter likely avoids the threading complications of the unsynchronized
test-and-set idiom you presented. In a case like this there is no advantage
to lazy initialization.
If your Logger class is from log4j it is already thread safe, of course.
One more approach is a static initializer:
public class Tester
{
private static final BufferedWriter logger;
static
{
String path = "/home/xi/Desktop/D2V/validation/";
try
{
logger = new BufferedWriter( new FileWriter(
new File( path, "log" )));
}
catch ( IOException exc )
{
String msg = "Cannot open log file \""+ path +"log\"";
throw new IllegalStateException( msg, exc );
}
}
...
}
This is like using the static init() method without naming the method. The
body of the static initializer could be the body of a static initialization
method like initLogger().
public class Tester
{
private static final BufferedWriter logger = initLogger();
...
}

Signature
Lew
xz - 07 Aug 2007 06:23 GMT
> The latter likely avoids the threading complications of the unsynchronized
> test-and-set idiom you presented. In a case like this there is no advantage
[quoted text clipped - 28 lines]
> body of the static initializer could be the body of a static initialization
> method like initLogger().
This is more close to what I wanted originally.
Thank you!