システム プロパティの範囲
少なくともSystem.setProperties
メソッドの API 仕様を読んでも、システム プロパティが JVM のすべてのインスタンスで共有されているかどうかはわかりませんでした。
調べるためにSystem.setProperty
、同じキーを使用して異なる値を使用して、システム プロパティを設定する 2 つの簡単なプログラムを作成しました。
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) {}
}
}
}
(上記の 2 つのプログラムを実行すると、無限ループに陥ることに注意してください!)
2 つの別個のプロセスを使用して 2 つのプログラムを実行すると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
は thread-safeProperties
であるため、それも同様であると予想していましたが、実際、Properties
クラスの API 仕様で確認されています。
このクラスはスレッド セーフです。複数のスレッドがProperties
、外部同期を必要とせずに 1 つのオブジェクトを共有できます。,シリアル化された形式