gpt4 book ai didi

java - 以下代码线程安全吗?

转载 作者:行者123 更新时间:2023-11-30 11:19:22 26 4
gpt4 key购买 nike

我想我已经实现了双重检查锁定模式,但不确定它是否安全或是否按预期工作。任何其他实现相同逻辑的逻辑都会非常有帮助。

public class OnProperties {

private static String dfltPropertyFile = "on.properties";
private static long refreshSecs = 120L;
private static Properties props;
private static long lastReadTimestamp = 0;


public static String getProperty(String propertyName, String dfltValue) {
long currentTimestamp = System.currentTimeMillis() / 1000L;

if (props == null
|| (refreshSecs > 0 && (currentTimestamp - lastReadTimestamp) > refreshSecs)) {
synchronized (props) {
if (props == null
|| (refreshSecs > 0 && (currentTimestamp - lastReadTimestamp) > refreshSecs)) {
lastReadTimestamp = currentTimestamp;
try {
loadProperties(dfltPropertyFile);
refreshSecs = getProperty("on.properties.refresh", 120L);
if (refreshSecs < 0L) {
refreshSecs = 0L;
}
} catch (Exception e) {
refreshSecs = 600L;
}
}
}
}

if (props == null) {
return dfltValue;
}

String propertyValue = props.getProperty(propertyName, dfltValue);

return propertyValue;
}

public static boolean getProperty(String propertyName, boolean dfltValue) {
boolean value = dfltValue;

String strValue = getProperty(propertyName, (String) null);
if (strValue != null) {
try {
value = Boolean.parseBoolean(strValue);
} catch (NumberFormatException e) {
// just keep the default
}

}
return value;
}

private static void loadProperties(String p_propertiesFile)
throws java.io.IOException, java.io.FileNotFoundException {
InputStream fileStream = new FileInputStream(p_propertiesFile);
props = new Properties();
props.load(fileStream);
fileStream.close();
}
}

一般多线程运行经常访问“getProperty”方法如下:

extDebug = OnProperties.getProperty("on.extdebug", false); 

最佳答案

原子值保证始终将完整的最新值返回给所有线程。在这种情况下,这可以防止出现许多多线程问题。仍然需要一点同步,但可以将其限制在最低限度。请参阅下面的实现:

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;

public class OnProperties {


private static int refreshIntervalDefaultSecs;
private static int refreshIntervalOnErrorSecs;

static {
setRefreshInterval(120);
}

private static final AtomicReference<Properties> propsRef = new AtomicReference<Properties>(new Properties());
private static final AtomicLong nextPropsLoad = new AtomicLong(0L);
private static final Object loadLock = new Object();

private static String dfltPropertyFile = "on.properties";

public static String getProperty(String key, String defaultValue) {

String value = getProperty(key);
if (value == null) {
value = defaultValue;
}
return value;
}

private static String getProperty(String key) {

reloadWhenNeeded();
return propsRef.get().getProperty(key);
}

private static void reloadWhenNeeded() {

long now = System.currentTimeMillis();
if (now > nextPropsLoad.get()) {
boolean reload = false;
synchronized(loadLock) {
if (now > nextPropsLoad.get()) {
// need loadLock because there is time between previous get()
// and next set()
updateNextPropsLoad(now, refreshIntervalDefaultSecs);
reload = true;
}
}
if (reload) {
reloadProps(now);
}
}
}

private static void updateNextPropsLoad(long now, int nextRefreshSecs) {
nextPropsLoad.set(now + nextRefreshSecs * 1000);
}

private static void reloadProps(long now) {

Properties p = new Properties();
FileInputStream in = null;

System.out.println("Reloading from " + new File(dfltPropertyFile).getAbsolutePath());

try {
p.load(in = new FileInputStream(new File(dfltPropertyFile)));
propsRef.set(p);
setRefreshInterval(getProperty("on.properties.refresh", 120));
updateNextPropsLoad(now, refreshIntervalDefaultSecs);
} catch (Exception e) {
updateNextPropsLoad(now, refreshIntervalOnErrorSecs);
} finally {
try { if (in != null) in.close(); } catch (Exception e) {
updateNextPropsLoad(now, refreshIntervalOnErrorSecs);
}
}
}

private static void setRefreshInterval(int refreshSecs) {

if (refreshSecs < 1) {
refreshSecs = 120;
}
refreshIntervalDefaultSecs = refreshSecs;
refreshIntervalOnErrorSecs = 5 * refreshSecs;
}

public static boolean getProperty(String key, boolean defaultValue) {

boolean value = defaultValue;
String svalue = getProperty(key);
if (svalue != null) {
try {
value = Boolean.valueOf(svalue);
} catch (Exception ignored) {}
}
return value;
}

public static int getProperty(String key, int defaultValue) {

int value = defaultValue;
String svalue = getProperty(key);
if (svalue != null) {
try {
value = Integer.valueOf(svalue);
} catch (Exception ignored) {}
}
return value;
}

public static void main(String[] args) {

System.out.println("Refresh value from file: " + getProperty("on.properties.refresh", 120));
System.out.println("No reload " + getProperty("does.not.exist", true));
System.out.println("Next reload after " + ((nextPropsLoad.get() - System.currentTimeMillis()) / 1000) + " seconds.");
}

}

实现的一个缺点是,选择一个线程将在选择文件中重新加载属性时会减慢。更好的方法是创建一个“看门狗”线程/计划任务,如果属性文件的修改日期已更改,则每(例如)五秒检查一次,然后触发重新加载(在这种情况下,属性的 AtomicReference 仍然会出现派上用场)。
另外请记住,存在一个逻辑线程问题:如果属性值相互关联(即一个值只有在另一个值也更新时才是正确的),重新加载可能会出现一个线程,其中包含不应该包含的旧值和新值被混合。解决这个问题的唯一方法是在使用属性的相互关联值的方法中保留对一组属性的引用(在这种情况下,像这样具有静态方法和变量的类并不方便)。

关于java - 以下代码线程安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23273378/

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