java - 使用分布式 JVM 缓存同步计算和结果

标签 java multithreading caching locking distributed

我想缓存一个昂贵的操作,并且不希望其他线程在不同的 JVM 中在给定时间执行相同的操作。我们保证在同一时间为同一计算获得至少 5 个近乎实时的请求,并且对简化这些请求没有任何控制。

我能想到的解决方案:

  1. These other threads could wait to acquire lock (Hazelcast) but if there are more threads the last one to acquire lock could spend a lot of time waiting to acquire the lock.

Is there was a way for these other threads to simply "wait for lock to be released" and NOT to acquire the lock as they are simply reading from cache?

  1. Use polling. First a blocking threadId=cache.putIfAbsent(key) returns which thread will process and others will keep polling another cache entry by threadId to get the result. This is a waste of polling, is there a way to "wait for a read from cache"?

  2. An actual distributed "Shared Reentrant Read Write Lock" seems to be the solution but Apache Curator library does not seem light weight. And I am looking for a simple async P2P distributed cache approach.



或者我如何使用 HazelCast 达到同样的效果?
总的来说,首先阻塞和避免计算(在我们的例子中是 CPU 和 IO 限制)不是比让所有线程计算并说使用数据库/缓存失败额外写入并返回第一个计算结果更好的方法吗?

最佳答案

不久前做了以下事情,首先有一个已经使用 Hazelcast 发布的解决方案:https://github.com/ThoughtWire/hazelcast-locks .

该库替代了分布式“共享可重入读写锁”,允许在写入时锁定,但在读取时不允许锁定,因此我们保证这只发生一次。我们面临的唯一问题是锁定释放通知的等待时间比我们预期的要长。除此之外,您必须在特定时间后以某种方式显式清理昂贵的锁,因为它们与特定的键相关联。

我们最终在请求到达 tomcat 容器之前在转发代理中实现了一个自定义逻辑,该容器基本上根据 key 将请求路由到特定服务器,并且我们基于相同的 key 在共享并发映射条目上设置了本地 JVM 锁工作。此外,清理逻辑要简单得多。

关于java - 使用分布式 JVM 缓存同步计算和结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29766666/

相关文章:

apache - 使用 VestaCP 在 Ubuntu 服务器上安装和配置 Varnish 缓存

java - 如何从第二个空格中分割java中的字符串?

java - Spring Security 3.1 和不安全的 HTTP channel

c# - 锁定对象字典以减少 C# 中的延迟?

c++ - 这对于等待使用std::future wait()返回的函数的CPU使用率更好,还是在循环中检查标志 sleep 一段时间?

php - 强制浏览器缓存图片

二叉树的缓存位置

java - 如何让2个线程共享数据? ( java )

java - Freemarker:如何使用 Multimap(或列表 map )

c# - 如何在C#中使用多线程下载单个文件