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).

sclass Cache<A> {
  O maker; // func -> A
  A value;
  long loaded;
  sbool debug;
  long changeCount;
  Lock lock = lock();
  
  *() {}
  *(O *maker) {}
  *(IF0<A> *maker) {}

  A get() {
    if (hasLock(lock)) ret value; // Must be called from within maker
    lock lock;
    if (loaded == 0) {
      value = make();
      changeCount++;
      loaded = sysNow();
    }
    ret value;
  }

  void clear {
    lock lock;
    if (debug && loaded != 0)
      print("Clearing cache");
    value = null;
    changeCount++;
    loaded = 0;
  }

  // clear if older than x seconds
  // 0 does not do anything
  void clear(double seconds) {
    lock lock;
    if (seconds != 0 && loaded != 0 && sysNow() >= loaded+seconds*1000)
      clear();
  }
  
  // override
  void set(A a) {
    lock lock;
    value = a;
    ++changeCount;
    loaded = sysNow();
  }
  
  A make() {
    ret (A) callF(maker);
  }
}

download  show line numbers  debug dex   

Travelled to 20 computer(s): aoiabmzegqzx, ayivmpnvhhik, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, irmadwmeruwu, ishqpsrjomds, jozkyjcghlvl, jtubtzbbkimh, lnbujpyubztb, lpdgvwnxivlt, mqqgnosmbjvj, onxytkatvevr, ppjhyzlbdabe, snaazhdonpnp, tslmcundralx, tvejysmllsmz, whxojlpjdney, 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: 354 / 6636
Version history: 7 change(s)
Referenced in: [show references]

Formerly at http://tinybrain.de/1007582 & http://1007582.tinybrain.de