01: // Copyright 2007 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: package org.apache.tapestry.ioc.internal.services;
16:
17: import org.apache.tapestry.ioc.ObjectCreator;
18: import org.apache.tapestry.ioc.internal.EagerLoadServiceProxy;
19: import org.apache.tapestry.ioc.services.RegistryShutdownListener;
20:
21: /**
22: * Invoked from a fabricated service delegate to get or realize (instantiate and configure) the
23: * service implementation. This includes synchronization logic, to prevent multiple threads from
24: * attempting to realize the same service at the same time (a service should be realized only once).
25: * The additional interfaces implemented by this class support eager loading of services (at
26: * application startup), and orderly shutdown of proxies.
27: */
28: public class JustInTimeObjectCreator implements ObjectCreator,
29: EagerLoadServiceProxy, RegistryShutdownListener {
30: private ObjectCreator _creator;
31:
32: private boolean _shutdown;
33:
34: private Object _object;
35:
36: private final String _serviceId;
37:
38: public JustInTimeObjectCreator(ObjectCreator creator,
39: String serviceId) {
40: _creator = creator;
41: _serviceId = serviceId;
42: }
43:
44: /**
45: * Checks to see if the proxy has been shutdown, then invokes
46: * {@link ObjectCreator#createObject()} if it has not already done so.
47: *
48: * @throws IllegalStateException
49: * if the registry has been shutdown
50: */
51: public synchronized Object createObject() {
52: if (_shutdown)
53: throw new IllegalStateException(ServiceMessages
54: .registryShutdown(_serviceId));
55:
56: if (_object == null) {
57: try {
58: _object = _creator.createObject();
59:
60: // And if that's successful ...
61:
62: _creator = null;
63: } catch (RuntimeException ex) {
64: throw new RuntimeException(ServiceMessages
65: .serviceBuildFailure(_serviceId, ex), ex);
66: }
67: }
68:
69: return _object;
70: }
71:
72: /**
73: * Invokes {@link #createObject()} to force the creation of the underlying service.
74: */
75: public void eagerLoadService() {
76: // Force object creation now
77:
78: createObject();
79: }
80:
81: /**
82: * Sets the shutdown flag and releases the object and the creator.
83: */
84: public synchronized void registryDidShutdown() {
85: _shutdown = true;
86: _object = null;
87: _creator = null;
88: }
89:
90: }
|