gpt4 book ai didi

java - 线程使用的 System.setProperty 会影响与外部网络元素通信的其他线程。如何解决?

转载 作者:搜寻专家 更新时间:2023-11-01 04:00:48 24 4
gpt4 key购买 nike

在我的应用程序中,我有两个线程。每个线程与不同的外部实体通信。

假设 T1 --> N1 & T2 --> N2(T1 & T2 是两个线程。N1 & N2 是外部实体。通信是基于 HTTPS 的 SOAP。)

N1 的供应商要求使用 key 存储文件 UPCC_client.store 进行身份验证,为此我们使用了以下代码,

System.setProperty("javax.net.ssl.keyStore", "<file path>");
System.setProperty("javax.net.ssl.keyStorePassword", "<password>");
System.setProperty("javax.net.ssl.trustStore","<file path>");
System.setProperty("javax.net.ssl.trustStorePassword", "<password>");

应用程序已重新启动,在 T1 线程中设置了上述属性,没有任何问题。 T2 开始遇到麻烦,因为 T1 设置的属性正在被 T2 使用。这背后的主要原因是 System.setProperty 是 JVM 范围。如何解决这个问题?

最佳答案

不过,我怀疑您在满足此要求方面存在设计问题。

我能想到的唯一解决方法是使您的属性成为 ThreadLocal。

public class ThreadLocalProperties extends Properties {
private final ThreadLocal<Properties> localProperties = new ThreadLocal<Properties>() {
@Override
protected Properties initialValue() {
return new Properties();
}
};

public ThreadLocalProperties(Properties properties) {
super(properties);
}

@Override
public String getProperty(String key) {
String localValue = localProperties.get().getProperty(key);
return localValue == null ? super.getProperty(key) : localValue;
}

@Override
public Object setProperty(String key, String value) {
return localProperties.get().setProperty(key, value);
}
}

// Make the properties thread local from here. This to be done globally once.
System.setProperties(new ThreadLocalProperties(System.getProperties()));

// in each thread.
System.setProperty("javax.net.ssl.keyStore", "my-key-store");

除非有任何混淆,否则 System.setProperties() 不仅会设置属性,还会替换集合及其实现。

// From java.lang.System
* The argument becomes the current set of system properties for use
* by the {@link #getProperty(String)} method.

public static void setProperties(Properties props) {
SecurityManager sm = getSecurityManager();
if (sm != null) {
sm.checkPropertiesAccess();
}
if (props == null) {
props = new Properties();
initProperties(props);
}
System.props = props;
}

通过使用此方法,系统属性的行为更改为线程本地调用 setProperty() 和 getProperty()

关于java - 线程使用的 System.setProperty 会影响与外部网络元素通信的其他线程。如何解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9579958/

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