< prev index next > src/java.base/share/classes/java/lang/ScopedValue.java
Print this page
/*
! * Copyright (c) 2020, 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2020, 2022, Red Hat Inc.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
/*
! * Copyright (c) 2020, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2020, 2022, Red Hat Inc.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
*
* {@snippet lang=java :
* private static final ScopedValue<String> NAME = ScopedValue.newInstance();
* ScopedValue.where(NAME, "duke").run(() -> {
! * try (var scope = new StructuredTaskScope<String>()) {
*
* // @link substring="fork" target="StructuredTaskScope#fork(java.util.concurrent.Callable)" :
* scope.fork(() -> childTask1());
* scope.fork(() -> childTask2());
* scope.fork(() -> childTask3());
*
* {@snippet lang=java :
* private static final ScopedValue<String> NAME = ScopedValue.newInstance();
* ScopedValue.where(NAME, "duke").run(() -> {
! * // @link substring="open" target="StructuredTaskScope#open()" :
+ * try (var scope = StructuredTaskScope.open()) {
*
* // @link substring="fork" target="StructuredTaskScope#fork(java.util.concurrent.Callable)" :
* scope.fork(() -> childTask1());
* scope.fork(() -> childTask2());
* scope.fork(() -> childTask3());
/**
* Returns the value of this scoped value if bound in the current thread, otherwise
* returns {@code other}.
*
! * @param other the value to return if not bound, can be {@code null}
* @return the value of the scoped value if bound, otherwise {@code other}
*/
public T orElse(T other) {
Object obj = findBinding();
if (obj != Snapshot.NIL) {
@SuppressWarnings("unchecked")
T value = (T) obj;
return value;
/**
* Returns the value of this scoped value if bound in the current thread, otherwise
* returns {@code other}.
*
! * @param other the value to return if not bound
* @return the value of the scoped value if bound, otherwise {@code other}
*/
public T orElse(T other) {
+ Objects.requireNonNull(other);
Object obj = findBinding();
if (obj != Snapshot.NIL) {
@SuppressWarnings("unchecked")
T value = (T) obj;
return value;
< prev index next >