简体   繁体   English

Java 7:在ServletContextListener中实现线程安全的可修改静态对象的最佳方法?

[英]Java 7: best way to implement thread-safe modifiable static object in ServletContextListener?

In a Java 7 Tomcat application, an object/structure obj containing several simple (String and numeric) types is frequently shared (read) by multiple servlet threads. 在Java 7 Tomcat应用程序中,包含多个简单(字符串和数字)类型的对象/结构obj被多个servlet线程频繁共享(读取)。 Periodically (every n minutes), all of obj 's members need to be refreshed simultaneously and atomically with respect to each other, and each of the servlet threads must always get the updated values whenever it reads the object. 周期性地(每隔n分钟),所有obj的成员都需要相对于彼此同时原子地进行刷新,并且每个Servlet线程在读取对象时都必须始终获取更新的值。 If no clients are connected, there is no need to refresh the values; 如果没有客户端连接,则无需刷新值;否则,无需刷新。 but as soon as one does connect (assuming at least n minutes have passed since the last update), the update needs to happen before the object is read. 但是一旦连接成功(假设自上次更新以来已经过去了至少n分钟),则需要读取对象之前进行更新。 Update: I should mention that currently, one of obj 's members is a timestamp indicating when the object data expires and needs to be refreshed. 更新:我应该提一下, obj的成员之一是一个时间戳,指示对象数据何时过期并且需要刷新。 If a solution, such as Guava Cache suggested in a comment below, already has this functionality built in, then all the better. 如果以下注释中建议的解决方案(例如Guava Cache)已经内置了此功能,那就更好了。

How would you implement this in Java 7? 您将如何在Java 7中实现这一点? At this point, simplicity and 'cleanliness' are more important than performance, but if you also want to provide a solution that's optimized for performance, please do. 在这一点上,简单和“清洁”比性能更重要,但是如果您还想提供针对性能进行优化的解决方案,请这样做。 I have an idea that may or may not work the way I expect, but would like to hear other opinions first. 我有一个想法可能无法达到预期的效果,但想先听听其他意见。 Thanks in advance. 提前致谢。

Use Guava Cache. 使用番石榴缓存。

In the context listener, do something like this: 在上下文侦听器中,执行以下操作:

LoadingCache<String, List<YourObjectType>> myCache = CacheBuilder.newBuilder()
    .expireAfterWrite(60, TimeUnit.MINUTES)
    .build(new CacheLoader<String, List<YourObjecttype>>() {
        public List<YourObjectType> load(String arg) {
            ...
        }
});

Save it to your servlet context: 将其保存到您的servlet上下文中:

ServletContext servletContext = servletContextEvent.getServletContext();
servletContext.setAttribute("myCache", myCache);

Then use it anywhere by getting the "myCache" attribute from the context object. 然后通过从上下文对象获取“ myCache”属性在任何地方使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM