001// Copyright 2006-2013 The Apache Software Foundation
002//
003// Licensed under the Apache License, Version 2.0 (the "License");
004// you may not use this file except in compliance with the License.
005// You may obtain a copy of the License at
006//
007// http://www.apache.org/licenses/LICENSE-2.0
008//
009// Unless required by applicable law or agreed to in writing, software
010// distributed under the License is distributed on an "AS IS" BASIS,
011// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
012// See the License for the specific language governing permissions and
013// limitations under the License.
014
015package org.apache.tapestry5.ioc.services;
016
017import org.apache.tapestry5.ioc.Invokable;
018
019/**
020 * Manages per-thread data, and provides a way for listeners to know when such data should be cleaned up. Typically,
021 * data is cleaned up at the end of the request (in a web application). Tapestry IoC has any number of objects that need
022 * to know when this event occurs, so that they can clean up any per-thread/per-request state.
023 * <p/>
024 * Due to <a href="https://issues.apache.org/jira/browse/TAPESTRY-2141">TAPESTRY-2141<a> (and the underlying JDK 1.5 bug
025 * <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5025230">5025230</a>), this service has expanded to
026 * manage per-thread data (not just end-of-request listeners).
027 */
028public interface PerthreadManager
029{
030    /**
031     * Adds a listener to the hub. All listeners are discarded at the {@link #cleanup()}.
032     *
033     * @param listener
034     *         to add
035     * @deprecated Deprecated in 5.4, use {@link #addThreadCleanupCallback(Runnable)} instead.
036     */
037    void addThreadCleanupListener(ThreadCleanupListener listener);
038
039    /**
040     * Adds a callback to be invoked when {@link #cleanup()} is invoked; callbacks are then removed.
041     *
042     * @param callback
043     * @since 5.4
044     */
045    void addThreadCleanupCallback(Runnable callback);
046
047    /**
048     * Immediately performs a cleanup of the thread, invoking all callback, then discarding all per-thread data
049     * stored by the manager (including the list of callbacks).
050     */
051    void cleanup();
052
053    /**
054     * Creates a value using a unique internal key.
055     *
056     * @since 5.2.0
057     */
058    <T> PerThreadValue<T> createValue();
059
060    /**
061     * Invokes {@link Runnable#run()}, providing a try...finally to {@linkplain #cleanup() cleanup} after.
062     *
063     * @since 5.2.0
064     */
065    void run(Runnable runnable);
066
067    /**
068     * Returns the result from the invocation, providing a try...finally to {@linkplain #cleanup() cleanup} after.
069     */
070    <T> T invoke(Invokable<T> invokable);
071}