org.wamblee.general.ThreadSpecificInvocationHandler Maven / Gradle / Ivy
The newest version!
/*
* Copyright 2005-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wamblee.general;
import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Invocation handler for thread-specific proxies.
*
* @author Erik Brakkee
*
* @param
*/
class ThreadSpecificInvocationHandler implements InvocationHandler,
Serializable {
/**
* We store a map of unique ids of invocation handlers to thread local
* storage of the service. In this way, serialiability of the generated
* proxy is obtained (required by framweorks such as wicket). Also,
* different factories will still be separate and never use the same
* threadlocal storage.
*/
private static Map STORAGE = initializeThreadLocal();
private static AtomicInteger COUNTER = new AtomicInteger();
private static Map initializeThreadLocal() {
Map map = new ConcurrentHashMap();
return map;
}
private int id;
private Class clazz;
/**
* Constructs the handler.
*
* @param aSvc
* Thread local for the service.
* @param aClass
* Service interface class.
*/
public ThreadSpecificInvocationHandler(ThreadLocal aSvc, Class aClass) {
id = COUNTER.incrementAndGet();
clazz = aClass;
STORAGE.put(id, aSvc);
}
@Override
public Object invoke(Object aProxy, Method aMethod, Object[] aArgs)
throws Throwable {
ThreadLocal local = STORAGE.get(id);
T actualSvc = local.get();
if (aMethod.getName().equals("toString") && actualSvc == null) {
return "Thread-specific proxy for '" + clazz.getName() + "' id = " +
id;
}
try {
return aMethod.invoke(actualSvc, aArgs);
} catch (InvocationTargetException e) {
throw e.getCause();
}
}
}