001/**
002 * Copyright (C) 2011 rwoo@gmx.de
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *         http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package com.googlecode.catchexception.throwable.internal;
017
018import java.lang.ref.WeakReference;
019
020/**
021 * Holds a caught throwable {@link ThreadLocal per Thread}.
022 * 
023 * @author rwoo
024 * 
025 */
026public class ThrowableHolder {
027
028    /**
029     * The container for the most recently caught throwable.
030     * <p>
031     * There is no need to use {@link WeakReference weak references} here as all
032     * the code is for testing so that we don't have to care about memory leaks.
033     */
034    private static final ThreadLocal<Throwable> caughtThrowable = new ThreadLocal<Throwable>();
035
036    /**
037     * Saves the given throwable in {@link #caughtThrowable}.
038     * 
039     * @param <E>
040     *            the type of the caught throwable
041     * @param caughtThrowable
042     *            the caught throwable
043     */
044    public static <E extends Throwable> void set(E caughtThrowable) {
045        ThrowableHolder.caughtThrowable.set(caughtThrowable);
046    }
047
048    /**
049     * @param <E>
050     *            the type of the caught throwable
051     * @return Returns the caught throwable. Returns null if there is no
052     *         throwable caught.
053     */
054    @SuppressWarnings("unchecked")
055    public static <E extends Throwable> E get() {
056        return (E) caughtThrowable.get();
057    }
058
059}