| 63 | } |
| 64 | |
| 65 | private static class WeakInterner<E> implements Interner<E> { |
| 66 | // MapMaker is our friend, we know about this type |
| 67 | private final MapMakerInternalMap<E, Dummy> map = |
| 68 | new MapMaker().weakKeys().keyEquivalence(Equivalence.equals()).makeCustomMap(); |
| 69 | |
| 70 | @Override |
| 71 | public E intern(E sample) { |
| 72 | while (true) { |
| 73 | // trying to read the canonical... |
| 74 | ReferenceEntry<E, Dummy> entry = map.getEntry(sample); |
| 75 | if (entry != null) { |
| 76 | E canonical = entry.getKey(); |
| 77 | if (canonical != null) { // only matters if weak/soft keys are used |
| 78 | return canonical; |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | // didn't see it, trying to put it instead... |
| 83 | Dummy sneaky = map.putIfAbsent(sample, Dummy.VALUE); |
| 84 | if (sneaky == null) { |
| 85 | return sample; |
| 86 | } else { |
| 87 | /* Someone beat us to it! Trying again... |
| 88 | * |
| 89 | * Technically this loop not guaranteed to terminate, so theoretically (extremely |
| 90 | * unlikely) this thread might starve, but even then, there is always going to be another |
| 91 | * thread doing progress here. |
| 92 | */ |
| 93 | } |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | private enum Dummy { |
| 98 | VALUE |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | /** |
| 103 | * Returns a function that delegates to the {@link Interner#intern} method of the given interner. |
nothing calls this directly
no test coverage detected