001 // Copyright 2009, 2011, 2012 The Apache Software Foundation
002 //
003 // Licensed under the Apache License, Version 2.0 (the "License");
004 // you may not use this file except in compliance with the License.
005 // You may obtain a copy of the License at
006 //
007 // http://www.apache.org/licenses/LICENSE-2.0
008 //
009 // Unless required by applicable law or agreed to in writing, software
010 // distributed under the License is distributed on an "AS IS" BASIS,
011 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
012 // See the License for the specific language governing permissions and
013 // limitations under the License.
014
015 package org.apache.tapestry5.ioc.internal.services;
016
017 import org.apache.tapestry5.ioc.ObjectCreator;
018 import org.apache.tapestry5.ioc.internal.util.LockSupport;
019
020 /**
021 * An {@link org.apache.tapestry5.ioc.ObjectCreator} that delegates to another
022 * {@link org.apache.tapestry5.ioc.ObjectCreator} and caches the result.
023 */
024 public class CachingObjectCreator<T> extends LockSupport implements ObjectCreator<T>
025 {
026 private boolean cached;
027
028 private T cachedValue;
029
030 private ObjectCreator<T> delegate;
031
032 public CachingObjectCreator(ObjectCreator<T> delegate)
033 {
034 this.delegate = delegate;
035 }
036
037 public T createObject()
038 {
039 try
040 {
041 acquireReadLock();
042
043 if (!cached)
044 {
045 cacheValueFromDelegate();
046 }
047
048 return cachedValue;
049 } finally
050 {
051 releaseReadLock();
052 }
053 }
054
055 private void cacheValueFromDelegate()
056 {
057 try
058 {
059 upgradeReadLockToWriteLock();
060
061 if (!cached)
062 {
063 cachedValue = delegate.createObject();
064 cached = true;
065 delegate = null;
066 }
067 } finally
068 {
069 downgradeWriteLockToReadLock();
070 }
071 }
072 }