如何使getFoo()和getBar()成为线程安全的?这样一来,一个线程可以调用getFoo()而另一个可以调用getBar()...即我不想在类级别锁上进行同步。
private static Foo foo;
private static Bar bar;
private static void initBar() {
bar = SomeOtherClass.getBarVal();
}
private static void initFoo() {
foo = SomeOtherClass.getFooVal();
}
public static Foo getFoo() {
if (foo == null) {
initFoo();
}
return foo;
}
public static Bar getBar() {
if (bar == null) {
initBar();
}
return bar;
}
您不需要锁定getFoo()
和getBar()
,仅需要init块:
private static volatile Foo foo;
private static volatile Bar bar;
private static final Object fooLock = new Object();
private static final Object barLock = new Object();
private static void initBar() {
bar = SomeOtherClass.getBarVal();
}
private static void initFoo() {
foo = SomeOtherClass.getFooVal();
}
public static Foo getFoo() {
if (foo == null) {
synchronized (fooLock) {
if (foo == null) {
initFoo();
}
}
}
return foo;
}
public static Foo getBar() {
if (bar == null) {
synchronized (barLock) {
if (bar == null) {
initBar();
}
}
}
return foo;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句