gpt4 book ai didi

java - 使用继承使类线程安全

转载 作者:行者123 更新时间:2023-12-03 12:57:08 27 4
gpt4 key购买 nike

假设我有一个这样的类:

package com.spotonsystems.bulkadmin.cognosSDK.util.Logging;

public class RecordLogging implements LittleLogging{

private LinkedList <String> logs;
private boolean startNew;

public RecordLogging() {
logs = new LinkedList<String>();
}

public void log(String log) {
logHelper(log);
startNew = true;
}

public void logPart(String log) {
logHelper(log);
startNew = false;
}

private void logHelper(String log){
// DO STUFF
}

public LinkedList<String> getResults() {
return logs;
}

}

现在假设我需要此代码的线程安全版本。我需要胎面安全版本来实现 LittleLogging。我希望线程安全副本与此类具有相同的行为,但我希望它是线程安全的。这样做是否安全:
package com.spotonsystems.bulkadmin.cognosSDK.util.Logging;

public class SyncRecordLogging extends RecordLogging {

public SyncRecordLoging() {
super();
}

public syncronized void log(String log) {
super.log(log);
}

public syncronized void logPart(String log) {
super.log(log);
}

public syncronized LinkedList<String> getResults() {
return logs;
}
}

额外问题:我应该在哪里查找有关同步和线程的文档

最佳答案

您可以改用组合。另请注意, getResults 创建列表的副本:

public class SyncRecordLogging  implements LittleLogging{

private final RecordLogging _log;

public SyncRecordLogging() {
_log = new RecordLogging();
}

public synchronized void log(String log) {
_log.log(log);
}

public synchronized void logPart(String log) {
_log.logPart(log);
}

public synchronized LinkedList<String> getResults() {
// returning copy to avoid 'leaking' the enderlying reference
return new LinkedList(_log.getResults());
}
}

最佳阅读: Java Concurrency In Practice

关于java - 使用继承使类线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6987711/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com