.
1-
synchronized(myValue) {
myValueSynchronized = someMethodToUpdateMyValue();
myValue = myValueSynchronized;
Thread.sleep(100);
}
, myValue. , Thread.sleep(100) . , myValue , , . . , .
. ReentrantLock String.
public static MetricsUpdater getInstance() {
if (theInstance == null) {
theInstance = new MetricsUpdater();
}
return theInstance;
}
Singleton . DCL (Double Checked Locking . ).
MetricsUpdater theInstance = new MetricsUpdate();. ,
sb.append(metrics.myValue);
.
1 - , someMethodToUpdateMyValue
class MetricsUpdater {
private static volatile MetricsUpdater theInstance;
public volatile String myValue;
public static MetricsUpdater getInstance() {
if (theInstance == null) {
synchronized(MetricsUpdate.class) {
if(theInstance == null) {
theInstance = new MetricsUpdater();
}
}
}
return theInstance;
}
private void updateMetrics() {
myValue = someMethodToUpdateMyValue();
}
}
2: , someMethodToUpdateMyValue
, /
myValue
class MetricsUpdater {
private static volatile MetricsUpdater theInstance;
public volatile String myValue;
private final Object lock = new Object();
public static MetricsUpdater getInstance() {
if (theInstance == null) {
synchronized(MetricsUpdate.class) {
if(theInstance == null) {
theInstance = new MetricsUpdater();
}
}
}
return theInstance;
}
private void updateMetrics() {
synchronized(lock) {
myValue = someMethodToUpdateMyValue();
}
}
}