欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

java设置属性的取值范围是多少_jvm-Java系统属性的范围

发布时间:2023/12/13 50 豆豆
生活随笔 收集整理的这篇文章主要介绍了 java设置属性的取值范围是多少_jvm-Java系统属性的范围 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

系统属性的范围

至少从阅读Properties方法的API规范后,我无法获得关于是否由JVM的所有实例共享系统属性的答案。

为了找出答案,我编写了两个快速程序,这些程序将使用相同的键但不同的值通过Properties设置系统属性:

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) {}

}

}

}

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

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

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

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

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

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

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

}

}

属性不是线程安全的吗?

Properties是线程安全的,因此我期望Properties也是这样,事实上,Properties类的API规范证实了这一点:

此类是线程安全的: 线程可以共享一个Properties 不需要外部物体 同步。,序列化表格

总结

以上是生活随笔为你收集整理的java设置属性的取值范围是多少_jvm-Java系统属性的范围的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。