2 * Copyright 2015-present Open Networking Foundation
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package io.atomix.utils.concurrent;
18 import java.util.concurrent.Executor;
20 import static com.google.common.base.Preconditions.checkState;
25 * The thread context is used by Catalyst to determine the correct thread on which to execute asynchronous callbacks.
26 * All threads created within Catalyst must be instances of {@link AtomixThread}. Once
27 * a thread has been created, the context is stored in the thread object via
28 * {@link AtomixThread#setContext(ThreadContext)}. This means there is a one-to-one relationship
29 * between a context and a thread. That is, a context is representative of a thread and provides an interface for firing
30 * events on that thread.
32 * Components of the framework that provide custom threads should use {@link AtomixThreadFactory}
33 * to allocate new threads and provide a custom {@link ThreadContext} implementation.
35 * @author <a href="http://github.com/kuujo">Jordan Halterman</a>
37 public interface ThreadContext extends AutoCloseable, Executor, Scheduler {
40 * Returns the current thread context.
42 * @return The current thread context or {@code null} if no context exists.
44 static ThreadContext currentContext() {
45 Thread thread = Thread.currentThread();
46 return thread instanceof AtomixThread ? ((AtomixThread) thread).getContext() : null;
50 * @throws IllegalStateException if the current thread is not a catalyst thread
52 static ThreadContext currentContextOrThrow() {
53 ThreadContext context = currentContext();
54 checkState(context != null, "not on a Catalyst thread");
59 * Returns a boolean indicating whether the current thread is in this context.
61 * @return Indicates whether the current thread is in this context.
63 default boolean isCurrentContext() {
64 return currentContext() == this;
68 * Checks that the current thread is the correct context thread.
70 default void checkThread() {
71 checkState(currentContext() == this, "not on a Catalyst thread");
75 * Returns whether the thread context is currently marked blocked.
77 * @return whether the thread context is currently marked blocked
82 * Marks the thread context as blocked.
87 * Marks the thread context as unblocked.