Java Web 应用程序同步问题

标签 java synchronized

假设我的网络应用程序中有一个名为“Foo”类的类。它有一个initialise() 方法,当使用Spring 创建bean 时会调用该方法。然后,initialise() 方法尝试加载外部服务并将其分配给一个字段。如果无法联系服务,则该字段将设置为空。

private Service service;

public void initialise() {
    // load external service
    // set field to the loaded service if contacted
    // set to field to null if service could not be contacted
}

当有人调用类“Foo”上的 get() 方法时,如果该服务是在initialise() 方法中启动的,则该服务将被调用。如果服务字段为空,我想尝试加载外部服务。

public String get() {
    if (service == null) {
        // try and load the service again
    }
    // perform operation on the service is service is not null
}

如果我这样做,是否可能会遇到同步问题?

最佳答案

工具包的答案是正确的。要解决这个问题,只需将 Foo 的initialise() 方法声明为同步即可。您可以将 Foo 重构为:

private Service service;

public synchronized void initialise() {
    if (service == null) {
        // load external service
        // set field to the loaded service if contacted
    }
}

public String get() {
    if (service == null) {            
        initialise(); // try and load the service again
    }
    // perform operation on the service is service is not null
}

关于Java Web 应用程序同步问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/227775/

相关文章:

java - 了解 java 中的 instanceof 以及 if 条件?

java - 使用四个规则之一对列表进行排序的最佳实践

java - 可变原子引用是个坏主意吗?

java - java中同步方法同时被访问会发生什么?

java - JPA 坚持 ManyToMany 与关联类?

java - 在 Eclipse 中使用 SQLite

java - 为什么多个线程能够访问同步块(synchronized block)?

java - 使用java中的AtomicReference获取/设置缓存中的值

java - Servlet 中的线程安全

java - 通过反射获取 map 项