java系统属性_Java系统属性的范围

本文探讨了Java中System.setProperty方法设置的系统属性是否在不同JVM实例间共享。通过实验发现,系统属性在每个JVM进程中独立,不相互影响。此外,文章还提供了一个程序示例来检查系统属性的变化,并确认Properties类是线程安全的。
摘要由CSDN通过智能技术生成

小编典典

系统属性的范围

至少通过阅读该System.setProperties方法的API规范,我无法获得有关是否由JVM的所有实例共享系统属性的答案。

为了找出答案,我编写了两个快速程序System.setProperty,它们使用相同的键,但使用不同的值通过设置系统属性:

class T1 {

public static void main(String[] s) {

System.setProperty("dummy.property", "42");

// Keep printing value of "dummy.property" forever.

while (true) {

System.out.println(System.getProperty("dummy.property"));

try {

Thread.sleep(500);

} catch (Exception e) {}

}

}

}

class T2 {

public static void main(String[] s) {

System.setProperty("dummy.property", "52");

// Keep printing value of "dummy.property" forever.

while (true) {

System.out.println(System.getProperty("dummy.property"));

try {

Thread.sleep(500);

} catch (Exception e) {}

}

}

}

(请注意,运行上面的两个程序会使它们陷入无限循环!)

事实证明,当使用两个单独的java进程运行两个程序时,在一个JVM进程中设置的属性值不会影响另一个JVM进程的值。

我应该补充一点,这是使用Sun的JRE 1.6.0_12的结果,并且至少在API规范中没有定义此行为(或者我找不到它),行为可能会有所不同。

是否有任何工具可以监视运行时更改

据我所知。但是,如果确实需要检查系统属性是否发生了变化,则可以一次保存该副本的副本Properties,然后将其与另一个调用进行比较System.getProperties-毕竟Properties是的子类Hashtable,因此比较将是以类似的方式执行。

以下是一个程序,该程序演示了一种检查系统属性是否已更改的方法。可能不是一个优雅的方法,但是它似乎可以完成它的工作:

import java.util.*;

class CheckChanges {

private static boolean isDifferent(Properties p1, Properties p2) {

Set> p1EntrySet = p1.entrySet();

Set> p2EntrySet = p2.entrySet();

// Check that the key/value pairs are the same in the entry sets

// obtained from the two Properties.

// If there is an difference, return true.

for (Map.Entry e : p1EntrySet) {

if (!p2EntrySet.contains(e))

return true;

}

for (Map.Entry e : p2EntrySet) {

if (!p1EntrySet.contains(e))

return true;

}

return false;

}

public static void main(String[] s)

{

// System properties prior to modification.

Properties p = (Properties)System.getProperties().clone();

// Modification of system properties.

System.setProperty("dummy.property", "42");

// See if there was modification. The output is "false"

System.out.println(isDifferent(p, System.getProperties()));

}

}

属性不是线程安全的吗?

Hashtable

是线程安全的

,因此我期望它Properties也是这样,实际上,Properties该类的API规范证实了这一点:

这个类是线程安全的:多个线程可以共享一个单一的Properties

,对象,而不需要外部同步,序列化表格

2020-09-15

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值