0

我有一个 jar,其中包含一个类,除其他外,该类读取属性并在构造函数中使用 getProperty 提取一些属性。

当我测试 jar 并通过提高并行线程使用 jmeter对其进行压力时,仅在某些情况下它会为某些属性返回 null。当我不强调它时,这不会发生。

我在 Windows 10 上使用 jdk-14。

这是我的源代码,由于版权原因做了一些修改。

提前感谢您的帮助!


public class Connector {

    private static properties;
    private static int port = 0;
    private static String host = null;
    private static int timeOutRead = 0;
    private static int timeOutConnect = 0;
    private static final Logger log = Logger.getLogger(Connector.class);

    public Connector() {
        try {
            Logg logg = new Logg();
            logg.initLoggerProperties();
            
            log.info("Constructor of Connector class");

            properties = readProperties("configurations/conector.properties");
            port = Integer.parseInt(properties.getProperty("port"));
            host = properties.getProperty("host");
            timeOutRead = Integer.parseInt(properties.getProperty("timeOutRead"));
            timeOutConnect = Integer.parseInt(properties.getProperty("timeOutConnect"));
            properties.clear();

            log.info(metodo + "port[" + port + "].");
            log.info(metodo + "host[" + host + "].");
            log.info(metodo + "timeOutRead[" + timeOutRead+ "].");
            log.info(metodo + "timeOutConnect["+ timeOutConnect + "].");
        } catch (Exception ex) {
            log.error(metodo
                    + "[ConectorCIO]::[ConectorCIO]::Se ha producido una exception del tipo:"
                    + ex.getMessage(), ex);
        }
    }
    
    
    private Properties readProperties(String pathAndName)
            throws FileNotFoundException, IOException {

        InputStream is = getClass().getClassLoader().getResourceAsStream(pathAndName);
        Properties properties = new Properties();
        properties.load(is);
        is.close();
        return properties;
    }
    
    
    //others functions
    
}
4

1 回答 1

1

您需要使您的字段非静态。那会解决你的问题。

问题在于以下两行:

properties = readProperties("configurations/conector.properties");
properties.clear();

当第一个线程正在填充属性时,其他线程可以在读取之前清除它。

当您从不同的线程访问相同的字段而不将它们标记为易失性时,这里也可能出现其他工件(这只是估计的描述,更多可以用谷歌搜索为 Java 内存模型(JMM))。

此外,您可以考虑将方法的所有代码放在synchronized块中。但请注意,没有线程能够并行执行代码,其他线程将等待。

PS看起来Singleton是你需要的。

于 2021-04-27T03:14:21.007 回答