Java EE:在这种情况下使我的上下文属性线程安全是否明智?

发布于 2024-11-05 09:41:40 字数 576 浏览 0 评论 0原文

我正在 Servlet 3.0 API 的帮助下为我的网站实现一个动态通知系统(类似于 Facebook)。我计划支持此功能的结构是:

  1. 在每个页面加载时,发送 XMLHTTP“get” 向服务器发出请求
  2. 允许服务器创建 AsyncContext 对象 从这些“获取”请求并存储 它们位于应用程序范围的映射中 由用户的网站 ID 键入
  3. 每当用户进行某项操作时, 产生通知,查询 应用程序范围的 ID 映射 用户的朋友,并使用 AsyncContext对象存储在那里,发送 通知每位朋友。
  4. 每位好友都会收到 通知。

我的问题是:是否有必要使该地图线程安全?在最坏的情况下,代表“通知发送用户”的函数会将通知发送到地图中的陈旧异步上下文,因为它对应的用户当前正在切换页面并且尚未切换发送新的 XMLHTTP 请求,或已注销。

然而,在每个页面加载时,我还有代码来检索数据库中比“上次检查日期”更新的所有通知,因此在页面加载时,通知用户不依赖于动态通知系统。因此,如果用户切换页面,他仍然会收到通知(显然,如果用户注销,则通知的概念不相关)。

考虑到这些信息,是否有任何场景需要映射是线程安全的?

I'm implementing a dynamic notification system (a la Facebook) for my website with the help of the Servlet 3.0 API. My planned structure to support this functionality is:

  1. On each page load, send an XMLHTTP "get"
    request to the server
  2. Allow the server to create AsyncContext objects
    from these "get" requests and store
    them in an application-scoped map
    keyed by the user's website ID
  3. Whenever a user engages in an action
    that spawns notification, query the
    application-scoped map for IDs of
    the user's friends, and using the
    AsyncContext objects stored there, send
    the notification to each friend.
  4. Each of the friends receive the
    notification.

My question is: is it necessary to make this map thread-safe? In the worst case scenario, a function acting on behalf of the "notification-sending-user" would send the notification to a stale async-context in the map, either because the user is it corresponds to is currently switching pages and has yet to send a new XMLHTTP request, or has logged out.

On each page load however, I also have code to retrieve all notifications in the database newer than the "last checked date", so on page load, notifying the user doesn't rely on the dynamic notification system. So, the user will still get the notification if he is switching pages (and obviously the concept of notifications is not relevant if the user logged out).

Given this information, are there any scenarios that would require the map to be thread safe?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

囍笑 2024-11-12 09:41:40

您可能不需要精确的一致性..但您仍然不希望任何线程在写入时读取正常的哈希图(添加可能会导致重新哈希并使获取线程陷入无限循环)。

此外,该计划无法很好地扩展到超过 1 个服务器。如果可以的话...只需使用 ConcurrentHashMap 即可。

You might not need exact consistency.. but you still don't want ANY threads reading to a normal hashmap while it is being written to (an add could cause a rehash and put the getting thread in an infinite loop).

Also, this plan won't scale super well past 1 server. If that is OK.... just use a ConcurrentHashMap.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文