View Javadoc
1   /*
2    * Copyright 2011-2024 the original author or authors.
3    *
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
7    *
8    *         https://www.apache.org/licenses/LICENSE-2.0
9    *
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.
15   */
16  package com.googlecode.catchexception.throwable;
17  
18  import java.lang.ref.WeakReference;
19  
20  /**
21   * Holds a caught throwable {@link ThreadLocal per Thread}.
22   */
23  final class ThrowableHolder {
24  
25      /**
26       * Prevent Instantiation of a new throwable holder.
27       */
28      private ThrowableHolder() {
29          // Preventing instantiation
30      }
31  
32      /**
33       * The container for the most recently caught throwable.
34       * <p>
35       * There is no need to use {@link WeakReference weak references} here as all the code is for testing so that we
36       * don't have to care about memory leaks.
37       */
38      private static final ThreadLocal<Throwable> caughtThrowable = new ThreadLocal<>();
39  
40      /**
41       * Saves the given throwable in {@link #caughtThrowable}.
42       *
43       * @param <E>
44       *            the type of the caught throwable
45       * @param caughtThrowable
46       *            the caught throwable
47       */
48      public static <E extends Throwable> void set(E caughtThrowable) {
49          ThrowableHolder.caughtThrowable.set(caughtThrowable);
50      }
51  
52      /**
53       * Gets the.
54       *
55       * @param <E>
56       *            the type of the caught throwable
57       *
58       * @return Returns the caught throwable. Returns null if there is no throwable caught.
59       */
60      @SuppressWarnings("unchecked")
61      public static <E extends Throwable> E get() {
62          return (E) caughtThrowable.get();
63      }
64  
65  }