java – 线程使用的System.setProperty会影响与外部网络元素通信
发布时间:2020-12-15 05:20:11 所属栏目:Java 来源:网络整理
导读:在我的应用程序中,我有两个线程.每个线程与不同的外部实体通信. 让我们说T1 – N1 T2 – N2(T1和T2是两个线程.N1和N2是外部实体.通信是基于HTTPS的SOAP.) N1的供应商请求使用密钥存储文件UPCC_client.store进行身份验证,同样我们使用了以下代码, System.setP
在我的应用程序中,我有两个线程.每个线程与不同的外部实体通信.
让我们说T1 – > N1& T2 – > N2(T1和T2是两个线程.N1和N2是外部实体.通信是基于HTTPS的SOAP.) N1的供应商请求使用密钥存储文件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()的线程本地 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |