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

36
LINES

< > BotCompany Repo | #1024132 // syncGetOrCreate2 - map lookup or create from class, return whether key is new

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

Libraryless. Click here for Pure Java version (2121L/14K).

1  
static <A, B> Pair<B, Bool> syncGetOrCreate2(Map<A, B> map, A key, Class<? extends B> c) ctex {
2  
  synchronized(map) {
3  
    B b = map.get(key);
4  
    if (b == null) {
5  
      map.put(key, b = c.newInstance());
6  
      ret pair(b, true);
7  
    }
8  
    ret pair(b, false);
9  
  }
10  
}
11  
12  
static <A, B> Pair<B, Bool> nuLike syncGetOrCreate2(Class<? extends B> c, Map<A, B> map, A key) {
13  
  ret syncGetOrCreate2(map, key, c);
14  
}
15  
16  
static <A, B> Pair<B, Bool> syncGetOrCreate2(Map<A, B> map, A key, F0<B> f) ctex {
17  
  synchronized(map) {
18  
    B b = map.get(key);
19  
    if (b == null) {
20  
      map.put(key, b = callF(f));
21  
      ret pair(b, true);
22  
    }
23  
    ret pair(b, false);
24  
  }
25  
}
26  
27  
static <A, B> Pair<B, Bool> syncGetOrCreate2(Map<A, B> map, A key, IF0<B> f) ctex {
28  
  synchronized(map) {
29  
    B b = map.get(key);
30  
    if (b == null) {
31  
      map.put(key, b = f!);
32  
      ret pair(b, true);
33  
    }
34  
    ret pair(b, false);
35  
  }
36  
}

Author comment

Began life as a copy of #1013935

download  show line numbers  debug dex  old transpilations   

Travelled to 6 computer(s): bhatertpkbcr, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #1024132
Snippet name: syncGetOrCreate2 - map lookup or create from class, return whether key is new
Eternal ID of this version: #1024132/4
Text MD5: 63323f5d15568fd073aa3e5c52f674a9
Transpilation MD5: f6f1e8d270ff17c4f6801c3d0455ae01
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2019-09-08 15:47:33
Source code size: 926 bytes / 36 lines
Pitched / IR pitched: No / No
Views / Downloads: 258 / 365
Version history: 3 change(s)
Referenced in: [show references]