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

27
LINES

< > BotCompany Repo | #1011383 // BetterThreadLocal - no memory leaks. sadly (but I bet it's _really_ ok! Has anyone checked whether it makes any difference in practice?) a bit slower than ThreadLocal

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

Libraryless. Click here for Pure Java version (4527L/25K).

1  
// Note: This does have the values problem (complicated values can cause memory leaks)
2  
sclass BetterThreadLocal<A> {
3  
  Map<Thread, A> map = newWeakHashMap();
4  
  
5  
  *() {}
6  
  *(A value) { set(value); }
7  
  
8  
  bool isSet() { ret map.containsKey(currentThread()); }
9  
  
10  
  A get() {
11  
    if (map.containsKey(currentThread()))
12  
      ret map.get(currentThread());
13  
    A value = initialValue();
14  
    set(value);
15  
    ret value;
16  
  }
17  
  
18  
  A get(Thread thread) {
19  
    ret thread == null ? null : map.get(thread);
20  
  }
21  
  
22  
  void set(A a) {
23  
    map.put(currentThread(), a);
24  
  }
25  
  
26  
  public A initialValue() { null; }
27  
}

Author comment

Also this can give you the value for another thread.

download  show line numbers  debug dex  old transpilations   

Travelled to 15 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, onxytkatvevr, ppjhyzlbdabe, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #1011383
Snippet name: BetterThreadLocal - no memory leaks. sadly (but I bet it's _really_ ok! Has anyone checked whether it makes any difference in practice?) a bit slower than ThreadLocal
Eternal ID of this version: #1011383/13
Text MD5: 0118518547504817300fd4ca958cad1e
Transpilation MD5: c31e697507eacc906cac33150ab4679c
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2021-11-01 23:53:35
Source code size: 622 bytes / 27 lines
Pitched / IR pitched: No / No
Views / Downloads: 602 / 1871
Version history: 12 change(s)
Referenced in: [show references]