计算机文章翻译(英译汉)0
Approach I (Critical Section)
This involves making the getFileLogger method a Critical Section so that
only one thread can ever execute it at any given point in time. This can be
accomplished by simply declaring the class-level method getFileLogger as
synchronized.
public class FileLogger implements Logger {
private static FileLogger logger;
private FileLogger() {
}public static synchronized FileLogger getFileLogger() {
if (logger == null) {
logger = new FileLogger();
}
return logger;
}
public synchronized void log(String msg) {
FileUtil futil = new FileUtil();
futil.writeToFile("log.txt”,msg, true, true);
}
}
This simple change turns the getFileLogger method into a Critical
Section and guarantees that no two threads ever execute the getFileLogger
method at the same time. This completely eliminates the possibility of the
FileLogger constructor getting invoked more than once inside the get-
FileLogger method.
Approach II (Static Early Initialization)
It is to be noted that synchronizing methods can have a significant effect on the
overall application performance. In general, synchronized methods run much
slower, as much as 100 times slower than their nonsynchronized counterparts. As
an alternative to declaring the getFileLogger method as synchronized, the
logger variable can be early initialized.
public class FileLogger implements Logger {
//Early Initialization
private static FileLogger logger = new FileLogger();
private FileLogger() {
}
public static FileLogger getFileLogger() {
return logger;
}
public synchronized void log(String msg) {
FileUtil futil = new FileUtil();
futil.writeToFile("log.txt”,msg, true, true);
}
}
This eliminates the need for any check or initialization inside the getFile-
Logger method. As a result, the getFileLogger becomes thread-safe automatically without having to declare it as synchronized.
PRACTICE QUESTIONS
1. Design a database connection class as a thread-safe singleton.
2. Design a printer spooler class as a thread-safe singleton.