01: // Copyright 2006 The Apache Software Foundation
02: //
03: // Licensed under the Apache License, Version 2.0 (the "License");
04: // you may not use this file except in compliance with the License.
05: // You may obtain a copy of the License at
06: //
07: // http://www.apache.org/licenses/LICENSE-2.0
08: //
09: // 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: /**
16: *
17: */package org.apache.tapestry.ioc.internal.services;
18:
19: import org.apache.tapestry.ioc.ObjectCreator;
20: import org.apache.tapestry.ioc.services.ThreadCleanupHub;
21: import org.apache.tapestry.ioc.services.ThreadCleanupListener;
22:
23: /**
24: * Provides per-thread implementations of services, along with end-of-request thread cleanup.
25: *
26: *
27: */
28: public class PerThreadServiceCreator extends ThreadLocal implements
29: ThreadCleanupListener, ObjectCreator {
30: private final ThreadCleanupHub _threadCleanupHub;
31:
32: private final ObjectCreator _delegate;
33:
34: public PerThreadServiceCreator(ThreadCleanupHub threadCleanupHub,
35: ObjectCreator delegate) {
36: _threadCleanupHub = threadCleanupHub;
37: _delegate = delegate;
38: }
39:
40: @Override
41: protected Object initialValue() {
42: // First time the value is accessed per thread, set up a callback to clear out the
43: // value (at the end of the request) and use the creator to create a new instance.
44:
45: _threadCleanupHub.addThreadCleanupListener(this );
46:
47: return _delegate.createObject();
48: }
49:
50: public Object createObject() {
51: // Get (or create) the service.
52: return get();
53: }
54:
55: public void threadDidCleanup() {
56: remove();
57: }
58:
59: }
|