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

30
LINES

< > BotCompany Repo | #1035367 // EphemeralObjectIDs - gives objects a temporary ID to reference them (using a weak reference)

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

Libraryless. Click here for Pure Java version (10231L/57K).

// ID 0 represents a null reference
// From there we count upwards. IDs are not reused when an object is GCed
sclass EphemeralObjectIDs {
  long idCounter;
  new WeakValueMap<Long, O> idToObject;
  Map<O, Long> objectToID = weakIdentityMap();
  
  selfType runnablesReferenceQueue(RunnablesReferenceQueue queue)  {
    idToObject.queue(queue);
    this;
  }
  
  synchronized long remember(O o) {
    if (o == null) ret 0;
    try object objectToID.get(o);
    long id = ++idCounter;
    idToObject.put(id, o);
    objectToID.put(o, id);
    ret id;
  }
  
  synchronized O get(long id) {
    if (id == 0) null;
    ret idToObject.get(id);
  }
  
  synchronized bool wasGarbageCollected(long id) {
    ret id > 0 && id <= idCounter && get(id) == null;
  }
}

download  show line numbers  debug dex  old transpilations   

Travelled to 3 computer(s): ekrmjmnbrukm, mowyntqkapby, mqqgnosmbjvj

No comments. add comment

Snippet ID: #1035367
Snippet name: EphemeralObjectIDs - gives objects a temporary ID to reference them (using a weak reference)
Eternal ID of this version: #1035367/5
Text MD5: 6d1359e692c0b15d83888401622da04a
Transpilation MD5: d456038002644810c653d74f877bd2b0
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2022-05-02 18:20:18
Source code size: 786 bytes / 30 lines
Pitched / IR pitched: No / No
Views / Downloads: 124 / 210
Version history: 4 change(s)
Referenced in: #1003674 - Standard Classes + Interfaces (LIVE continued in #1034167)