Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

52
LINES

< > BotCompany Repo | #1007582 // Cache - single-object cache

JavaX fragment (include) [tags: use-pretranspiled]

Libraryless. Click here for Pure Java version (2230L/14K).

1  
sclass Cache<A> {
2  
  O maker; // func -> A
3  
  A value;
4  
  long loaded;
5  
  sbool debug;
6  
  long changeCount;
7  
  Lock lock = lock();
8  
  
9  
  *() {}
10  
  *(O *maker) {}
11  
  *(IF0<A> *maker) {}
12  
13  
  A get() {
14  
    if (hasLock(lock)) ret value; // Must be called from within maker
15  
    lock lock;
16  
    if (loaded == 0) {
17  
      value = make();
18  
      changeCount++;
19  
      loaded = sysNow();
20  
    }
21  
    ret value;
22  
  }
23  
24  
  void clear {
25  
    lock lock;
26  
    if (debug && loaded != 0)
27  
      print("Clearing cache");
28  
    value = null;
29  
    changeCount++;
30  
    loaded = 0;
31  
  }
32  
33  
  // clear if older than x seconds
34  
  // 0 does not do anything
35  
  void clear(double seconds) {
36  
    lock lock;
37  
    if (seconds != 0 && loaded != 0 && sysNow() >= loaded+seconds*1000)
38  
      clear();
39  
  }
40  
  
41  
  // override
42  
  void set(A a) {
43  
    lock lock;
44  
    value = a;
45  
    ++changeCount;
46  
    loaded = sysNow();
47  
  }
48  
  
49  
  A make() {
50  
    ret (A) callF(maker);
51  
  }
52  
}

download  show line numbers  debug dex  old transpilations   

Travelled to 30 computer(s): aoiabmzegqzx, ayivmpnvhhik, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, ekrmjmnbrukm, gwrvuhgaqvyk, irmadwmeruwu, ishqpsrjomds, jcllbfdqhrgy, jozkyjcghlvl, jtubtzbbkimh, lnbujpyubztb, lpdgvwnxivlt, mowyntqkapby, mqqgnosmbjvj, omdjrrnzbjjv, onxytkatvevr, podlckwnjdmb, ppjhyzlbdabe, pyentgdyhuwx, pzhvpgtvlbxg, snaazhdonpnp, tslmcundralx, tvejysmllsmz, vouqrxazstgt, whxojlpjdney, wnsclhtenguj, wtqryiryparv, xrpafgyirdlv

No comments. add comment

Snippet ID: #1007582
Snippet name: Cache - single-object cache
Eternal ID of this version: #1007582/8
Text MD5: 1c7a801826d0296ca3ada8a9287b1745
Transpilation MD5: 14cc7c10e9e4454aaf297dbd6cd92493
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2019-11-11 14:04:33
Source code size: 949 bytes / 52 lines
Pitched / IR pitched: No / No
Views / Downloads: 677 / 9620
Version history: 7 change(s)
Referenced in: [show references]