1 // Copyright 2008 The Apache Software Foundation
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package org.apache.tapestry5.ioc.internal;
16
17 import org.apache.tapestry5.ioc.OperationTracker;
18 import org.apache.tapestry5.ioc.internal.util.Invokable;
19 import org.slf4j.Logger;
20
21 /**
22 * Manages a per-thread OperationTracker using a ThreadLocal.
23 */
24 public class PerThreadOperationTracker implements OperationTracker
25 {
26 private final Logger logger;
27
28 private final ThreadLocal<OperationTrackerImpl> perThread = new ThreadLocal<OperationTrackerImpl>()
29 {
30 @Override
31 protected OperationTrackerImpl initialValue()
32 {
33 return new OperationTrackerImpl(logger);
34 }
35 };
36
37 public PerThreadOperationTracker(Logger logger)
38 {
39 this.logger = logger;
40 }
41
42 synchronized OperationTracker get()
43 {
44 return perThread.get();
45 }
46
47 synchronized void cleanup()
48 {
49 if (perThread.get().isEmpty()) perThread.remove();
50 }
51
52 public void run(String description, Runnable operation)
53 {
54 try
55 {
56 get().run(description, operation);
57 }
58 finally
59 {
60 cleanup();
61 }
62 }
63
64 public <T> T invoke(String description, Invokable<T> operation)
65 {
66 try
67 {
68 return get().invoke(description, operation);
69 }
70 finally
71 {
72 cleanup();
73 }
74 }
75 }