计算机被用来看文章,翻译,计算机文章翻译(英译汉)

计算机文章翻译(英译汉)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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值