Skip to content
Permalink
Browse files
8269172: Add java.util.Objects.newIdentity method
Reviewed-by: mchung
  • Loading branch information
Roger Riggs committed Jun 23, 2021
1 parent 936d430 commit bb1071183ffdce1c8ed4ca09790437d8543df831
Showing with 28 additions and 15 deletions.
  1. +11 −14 src/java.base/share/classes/java/util/Objects.java
  2. +17 −1 test/jdk/java/util/Objects/BasicObjectsTest.java
@@ -423,20 +423,6 @@ public static long getObjectSize(Object o) {
return Unsafe.getUnsafe().getObjectSize(o);
}

/**
* Returns a new Object implementing the {@code IdentityObject} interface.
* The object is a unique {@link IdentityObject} suitable for all purposes
* for which {@code new Object{}} was used including synchronization,
* mutexes and unique placeholders.
*
* @return a new Object implementing the IdentityObject interface
* @since Valhalla
*/
public static IdentityObject newIdentity() {
// Return a new instance of an anonymous inner class.
return new IdentityObject() { };
}

/**
* Checks if the {@code index} is within the bounds of the range from
* {@code 0} (inclusive) to {@code length} (exclusive).
@@ -512,4 +498,15 @@ long checkFromToIndex(long fromIndex, long toIndex, long length) {
long checkFromIndexSize(long fromIndex, long size, long length) {
return Preconditions.checkFromIndexSize(fromIndex, size, length, null);
}
/**
* {@return a new instance of an unspecified class}
* The object has a unique identity; no other references to it exist.
* It can be used for synchronization, or where a placeholder Object is needed.
* Use this method to avoid relying on the {@linkplain Object#Object() Object constructor}.
*
* @since 17
*/
public static Object newIdentity() {
return new Object() {};
}
}
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2009, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -45,6 +45,7 @@ public static void main(String... args) {
errors += testIsNull();
errors += testNonNull();
errors += testNonNullOf();
errors += testNewIdentity();
if (errors > 0 )
throw new RuntimeException();
}
@@ -275,4 +276,19 @@ private static int testNonNullOf() {
}
return errors;
}

private static int testNewIdentity() {
int errors = 0;

Object o1 = Objects.newIdentity();
Object o2 = Objects.newIdentity();

if (o1 == null || o2 == null)
errors += 1;

if (o1 == o2)
errors += 1;

return errors;
}
}

0 comments on commit bb10711

Please sign in to comment.