考虑这样一种情况,我们有一个 Controller ,它有两个使用相同 Controller 字段的操作方法。该字段应该延迟初始化。
public class SomeController extends Controller {
private static volatile Resource resource;
private static Resource getResource() {
if (resource == null) {
synchronized (SomeController.class) {
if (resource == null) {
resource = new Resource();
}
}
}
return resource;
}
public static void action1() {
getResource().doSomeAction();
}
public static void action2() {
getResource().doSomeAnotherAction();
}
}
使用 Play Framework 同步公共(public)资源的更好方法是什么?考虑资源应该延迟初始化。
谢谢, 阿德里安
最佳答案
与 Play 或其他使用常规 servlet 的 servlet 容器(tomcat 等)中的延迟加载类(字段)没有区别。您的带有双重检查锁定的代码应该可以正常工作。但我建议您避免双重检查锁定(即使它没有损坏),只需使您的方法同步即可。
关于java - Play 中的现场同步! Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9315743/