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  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: 678 / 9620
Version history: 7 change(s)
Referenced in: #1019849 - Loadable Utils
#1029927 - Loadable Utils v2 (old)
#1030952 - Loadable Utils for Gazelle BEA [LIVE, see #1030953, edited by #1030951]
#1031186 - Loadable Utils v5
#1032272 - Loadable Utils for Gazelle BEA [backup]
#1032708 - Secret BEA Utils [purposely different from regular utils]
#1033505 - Loadable Utils for Gazelle V [stable version]
#1033861 - Loadable Utils for Gazelle 22 [dev version]
#1034167 - Standard Classes + Interfaces (LIVE, continuation of #1003674)