2 * Copyright 2005-2010 the original author or authors.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 package org.wamblee.general;
18 import java.io.Serializable;
19 import java.lang.reflect.InvocationHandler;
20 import java.lang.reflect.InvocationTargetException;
21 import java.lang.reflect.Method;
23 import java.util.concurrent.ConcurrentHashMap;
24 import java.util.concurrent.atomic.AtomicInteger;
27 * Invocation handler for thread-specific proxies.
29 * @author Erik Brakkee
33 class ThreadSpecificInvocationHandler<T> implements InvocationHandler,
37 * We store a map of unique ids of invocation handlers to thread local
38 * storage of the service. In this way, serialiability of the generated
39 * proxy is obtained (required by framweorks such as wicket). Also,
40 * different factories will still be separate and never use the same
41 * threadlocal storage.
43 private static Map<Integer, ThreadLocal> STORAGE = initializeThreadLocal();
45 private static AtomicInteger COUNTER = new AtomicInteger();
47 private static Map<Integer, ThreadLocal> initializeThreadLocal() {
48 Map<Integer, ThreadLocal> map = new ConcurrentHashMap<Integer, ThreadLocal>();
56 * Constructs the handler.
59 * Thread local for the service.
61 * Service interface class.
63 public ThreadSpecificInvocationHandler(ThreadLocal aSvc, Class aClass) {
64 id = COUNTER.incrementAndGet();
66 STORAGE.put(id, aSvc);
70 public Object invoke(Object aProxy, Method aMethod, Object[] aArgs)
73 ThreadLocal<T> local = STORAGE.get(id);
74 T actualSvc = local.get();
75 if (aMethod.getName().equals("toString") && actualSvc == null) {
76 return "Thread-specific proxy for '" + clazz.getName() + "' id = " +
80 return aMethod.invoke(actualSvc, aArgs);
81 } catch (InvocationTargetException e) {