On Sat, Jun 21, 2008 at 9:35 AM, Tim Peierls <[EMAIL PROTECTED]> wrote:

> While it's currently true of Restlet that each Resource instance is
> confined to a single thread, this may change in the future, so it would be
> unwise to rely too heavily on it.
>

Getting a litle OT, here's a utility that can be used to prevent accidental
(or malicious) attempts to access a thread-confined object from another
thread:

public class ThreadConfined<T> implements InvocationHandler {

    public static <T> T threadConfinedInstance(Class<T> type, T t) {
        return type.cast(Proxy.newProxyInstance(type.getClassLoader(),
                                                new Class<?>[] { type },
                                                new ThreadConfined<T>(t)));
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws
Throwable {
        T t = holder.get();
        if (t == null) {
            throw new IllegalStateException(
                "Attempt to access thread-confined instance from other
thread.");
        }
        return method.invoke(t, args);
    }

    private ThreadConfined(T t) {
        holder.set(t);
    }

    private final ThreadLocal<T> holder = new ThreadLocal<T>();
}

Only works when T is an interface.

To use this with the BoundedPool example in my earlier response, you'd have
to modify BoundedPool to take a Class<T> argument. The advantage would be
that BoundedPool.perform(task) could pass a thread-confined instance to
task.perform(t), thereby preventing leaks to other threads.

--tim

Reply via email to