< prev index next > src/java.base/share/classes/java/util/Optional.java
Print this page
* (returns a default value if no value is present) and
* {@link #ifPresent(Consumer) ifPresent()} (performs an
* action if a value is present).
*
* <p>This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>
! * class; programmers should treat instances that are
! * {@linkplain #equals(Object) equal} as interchangeable and should not
! * use instances for synchronization, or unpredictable behavior may
! * occur. For example, in a future release, synchronization may fail.
*
* @apiNote
* {@code Optional} is primarily intended for use as a method return type where
* there is a clear need to represent "no result," and where using {@code null}
* is likely to cause errors. A variable whose type is {@code Optional} should
* (returns a default value if no value is present) and
* {@link #ifPresent(Consumer) ifPresent()} (performs an
* action if a value is present).
*
* <p>This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>
! * class; programmers should treat instances that are {@linkplain #equals(Object) equal}
! * as interchangeable and should not use instances for synchronization, mutexes, or
! * with {@linkplain java.lang.ref.Reference object references}.
! *
+ * <div class="preview-block">
+ * <div class="preview-comment">
+ * When preview features are enabled, {@code Optional} is a {@linkplain Class#isValue value class}.
+ * Use of value class instances for synchronization, mutexes, or with
+ * {@linkplain java.lang.ref.Reference object references} result in
+ * {@link IdentityException}.
+ * </div>
+ * </div>
*
* @apiNote
* {@code Optional} is primarily intended for use as a method return type where
* there is a clear need to represent "no result," and where using {@code null}
* is likely to cause errors. A variable whose type is {@code Optional} should
* instance.
*
* @param <T> the type of value
* @since 1.8
*/
+ @jdk.internal.MigratedValueClass
@jdk.internal.ValueBased
public final class Optional<T> {
/**
* Common instance for {@code empty()}.
*/
< prev index next >