系统属性的范围
至少通过阅读该
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<Map.Entry<Object, Object>> p1EntrySet = p1.entrySet(); Set<Map.Entry<Object, Object>> 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<Object, Object> e : p1EntrySet) { if (!p2EntrySet.contains(e)) return true; } for (Map.Entry<Object, Object> 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
,对象,而不需要外部同步,序列化表格



