0

Hi I have Map object which is getting its values from MySQL table. This map is initialize inside servlet init() method in order to save many database call. What if the value in sql table change, can I Update Map object's value without restarting Servlet because init() method is called only once. Can I make an update button for this purpose. Thanks.

4

1 回答 1

1

是的,你应该可以。假设您的 servlet 类似于(减去异常)

public class MyServlet extends HttpServlet {
    private volatile Map<String, String> properties;
    private Object lock = new Object();

    public void init() {
        properties = ...; // from jdbc call
    }

    ...
}

您将有一个可以更改的Map参考。properties这里危险的部分是多个线程可能正在访问映射,所以如果你想改变它,你需要让它volatile对所有 s 可见,Thread并且你需要在一个锁上同步(或使用一个Lock对象),这样Thread如果需要,请等待进行更改。

例如,您可能有一个update执行POST. 你doPost()看起来像这样

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    Map<String, String> newProperties = ...; // get new map from jdbc call
    synchronized (lock) {
        properties = newProperties;
    }
}

就是这样。地图现在properties保存了数据库中最新的属性(或其他)。

于 2013-09-15T13:06:51.420 回答