系统属性的范围
至少通过阅读 API 规范System.setProperties http://java.sun.com/javase/6/docs/api/java/lang/System.html#setProperties(java.util.Properties)方法,我无法得到系统属性是否由 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 http://java.sun.com/javase/6/docs/api/java/util/Properties.html是一个子类Hashtable http://java.sun.com/javase/6/docs/api/java/util/Hashtable.html,因此将以类似的方式进行比较。
以下程序演示了检查系统属性是否已更改的方法。可能不是一个优雅的方法,但它似乎完成了它的工作:
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 http://java.sun.com/javase/6/docs/api/java/util/Hashtable.html 是线程安全的,所以我期待着Properties
事实上,API 规范也是如此Properties http://java.sun.com/javase/6/docs/api/java/util/Properties.html类证实了这一点:
这个类是线程安全的:多个
线程可以共享一个Properties
不需要外部的对象
同步.,序列化形式 http://java.sun.com/javase/6/docs/api/serialized-form.html#java.util.Properties