且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何以线程安全的方式在DAO中缓存信息

更新时间:2022-05-21 22:12:04

如果你只是想快速滚动自己的缓存解决方案,请查看这篇关于JavaSpecialist的文章,这是对 Java Concurrency in Practice 作者: Brian Goetz

If you just want a quick roll-your own caching solution, have a look at this article on JavaSpecialist, which is a review of the book Java Concurrency in Practice by Brian Goetz.

它介绍了使用 FutureTask ConcurrentHashMap

这种方式确保只有一个并发线程触发长时间运行的计算(在您的情况下,您的数据库调用在您的DAO)。

The way this is done ensures that only one concurrent thread triggers the long running computation (in your case, your database calls in your DAO).

如果需要,您必须修改此解决方案以添加缓存过期。

You'd have to modify this solution to add cache expiry if you need it.

另一个关于自己缓存的想法是垃圾收集。如果不为缓存使用WeakHashMap,那么GC将无法释放缓存使用的内存(如果需要)。如果你缓存不常访问的数据(但是数据仍然值得缓存,因为它很难计算),那么你可能想通过使用WeakHashMap在内存不足时帮助垃圾收集器。

The other thought about caching it yourself is garbage collection. Without using a WeakHashMap for your cache, then the GC wouldn't be able to release the memory used by the cache if needed. If you are caching infrequently accessed data (but data that was still worth caching since it is hard to compute), then you might want to help out the garbage collector when running low on memory by using a WeakHashMap.