Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Build an efficient and scalable result cache

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Network Security >

Share

Shulou(Shulou.com)06/01 Report--

Extracted from

Public interface Computable {V comput (An arg);}

Import java.util.concurrent.*;/** * build an efficient scalable result cache *

* author: shiruiqiang * time: 31 arg 23:11 * * / public class Memoizer implements Computable {private final ConcurrentHashMap cache = new ConcurrentHashMap (); private Computable c; public Memoizer (Computable c) {this.c = c;} public V comput (An arg) {while (true) {Future f = cache.get (arg) If (f = = null) {/ / check whether it already exists in the cache, and if not, create Callable task = new Callable () {@ Override public V call () throws Exception {return c.comput (arg);}} FutureTask ft = new FutureTask (task); f = cache.putIfAbsent (arg, ft); / / Atomic operation, if (f = = null) {/ / if there is no such result in the cache, execute the task calculation result f = ft; ft.run () }} try {return f.get (); / / Block, waiting for the result. If it is already in the cache, it will not block} catch (CancellationException e) {cache.remove (arg, f);} catch (Exception e) {e.printStackTrace ();}

The above code has many benefits.

1: calculation is isolated from cache and decoupled

2: thread safety

3: support concurrency

4: do not repeat calculation when concurrent, efficient

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Network Security

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report