| 311 | } |
| 312 | |
| 313 | @VisibleForTesting |
| 314 | static class ArbitraryOrdering extends Ordering<Object> { |
| 315 | @SuppressWarnings("deprecation") // TODO(kevinb): ? |
| 316 | private final Map<Object, Integer> uids = Platform.tryWeakKeys(new MapMaker()).makeComputingMap(new Function<Object, Integer>() { |
| 317 | final AtomicInteger counter = new AtomicInteger(0); |
| 318 | |
| 319 | @Override |
| 320 | public Integer apply(Object from) { |
| 321 | return counter.getAndIncrement(); |
| 322 | } |
| 323 | }); |
| 324 | |
| 325 | @Override |
| 326 | public int compare(Object left, Object right) { |
| 327 | if (left == right) { |
| 328 | return 0; |
| 329 | } else if (left == null) { |
| 330 | return -1; |
| 331 | } else if (right == null) { |
| 332 | return 1; |
| 333 | } |
| 334 | int leftCode = identityHashCode(left); |
| 335 | int rightCode = identityHashCode(right); |
| 336 | if (leftCode != rightCode) { |
| 337 | return leftCode < rightCode ? -1 : 1; |
| 338 | } |
| 339 | |
| 340 | // identityHashCode collision (rare, but not as rare as you'd think) |
| 341 | int result = uids.get(left).compareTo(uids.get(right)); |
| 342 | if (result == 0) { |
| 343 | throw new AssertionError(); // extremely, extremely unlikely. |
| 344 | } |
| 345 | return result; |
| 346 | } |
| 347 | |
| 348 | @Override |
| 349 | public String toString() { |
| 350 | return "Ordering.arbitrary()"; |
| 351 | } |
| 352 | |
| 353 | /* |
| 354 | * We need to be able to mock identityHashCode() calls for tests, because it |
| 355 | * can take 1-10 seconds to find colliding objects. Mocking frameworks that |
| 356 | * can do magic to mock static method calls still can't do so for a system |
| 357 | * class, so we need the indirection. In production, Hotspot should still |
| 358 | * recognize that the call is 1-morphic and should still be willing to |
| 359 | * inline it if necessary. |
| 360 | */ |
| 361 | |
| 362 | int identityHashCode(Object object) { |
| 363 | return System.identityHashCode(object); |
| 364 | } |
| 365 | } |
| 366 | |
| 367 | // Constructor |
| 368 |
nothing calls this directly
no test coverage detected