Java – system. Java used by threads Setproperty affects other threads that communicate with external network elements How?

In my application, I have two threads Each thread communicates with a different external entity

Let's say T1 – > N1 & T2 – > N2 (T1 and T2 are two threads. N1 and N2 are external entities. Communication is HTTPS based soap.)

The supplier of N1 requests to use the key storage file UPCC_ client. Store for authentication. Similarly, we use the following code,

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>");

The application has been restarted with the above properties set in T1 thread without any problem T2 began to have trouble because the attribute set by T1 was used by T2 The main reason behind this is system Setproperty is the JVM scope How to solve this problem?

Solution

I suspect you have a design problem, but you have this requirement

The only way to solve this problem is to make your property 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");

Unless there is any confusion, system Setproperties () not only sets properties, but replaces the collection and its implementation

// 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;
}

By using this method, the behavior of the system property is changed to the local thread calling setproperty () and getproperty ()

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>