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

93
LINES

< > BotCompany Repo | #1004094 - TimedCache - caches an object for a specified time [thread-safe]

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

Libraryless. Click here for Pure Java version (1938L/12K).

static class TimedCache<A> {
  long timeout;
  volatile A value; // volatile for peek()
  O function;
  long set;
  Lock lock = lock();
  bool keepValueWhileCalculating; // special mode to make peek() always return something
  
  // stats
  int stores, fails, hits;
  
  *(double timeoutSeconds, O function) {
    this(function, timeoutSeconds);
  }
  
  *(O function, double timeoutSeconds) {
    this(timeoutSeconds);
    this.function = function;
  }

  // 0 = no timeout  
  *(double timeoutSeconds) {
    timeout = toMS(timeoutSeconds);
  }
  
  A set(A a) {
    lock lock;
    ++stores;
    value = a;
    set = now();
    ret a;
  }
  
  bool has() {
    lock lock;
    clean();
    if (set != 0) {
      ++hits;
      true;
    }
    ++fails;
    false;
  }
  
  A get() {
    lock lock;
    if (function != null) ret get(function);
    clean();
    if (set != 0) ++hits; else ++fails;
    ret value;
  }
  
  A get(O makerFunction) {
    lock lock;
    if (keepValueWhileCalculating) {
      if (value == null || shouldClean())
        set((A) callF(makerFunction));
      ret value;
    } else {
      ret this.has() ? getNoClean() : set((A) callF(makerFunction));
    }
  }
  
  A getNoClean() {
    lock lock; // lock to wait for potentially running calculation
    ret value;
  }
  
  // clear if timed out
  void clean() {
    lock lock;
    if (shouldClean()) clear();
  }
  
  bool shouldClean() {
    ret timeout > 0 && now() > set+timeout;
  }
  
  // clear now
  void clear() {
    lock lock;
    set = 0;
    value = null;
  }
  
  S stats() {
    ret "Stores: " + stores + ", hits: " + hits + ", fails: " + fails;
  }
  
  A peek() {
    ret value;
  }
}

download  show line numbers  debug dex   

Travelled to 18 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, ddnzoavkxhuk, fehiwqupcyrn, gwrvuhgaqvyk, ishqpsrjomds, lhdilzshxjzv, lpdgvwnxivlt, mqqgnosmbjvj, onxytkatvevr, pzhvpgtvlbxg, sawdedvomwva, tslmcundralx, tvejysmllsmz, wtqryiryparv, xprdwmaupziu

No comments. add comment

Snippet ID: #1004094
Snippet name: TimedCache - caches an object for a specified time [thread-safe]
Eternal ID of this version: #1004094/7
Text MD5: 52d20f8a91fb3ad95b135d0445fea9b6
Transpilation MD5: 5182fce10afed0d12f845aaa3a2b9b6d
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2019-08-08 14:08:41
Source code size: 1767 bytes / 93 lines
Pitched / IR pitched: No / No
Views / Downloads: 402 / 2306
Version history: 6 change(s)
Referenced in: [show references]

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