栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Java系统属性的范围

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java系统属性的范围

系统属性的范围

至少通过阅读该

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

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



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/514949.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号