blob: 35c8e11f043a2473767d1a65a0ac9c51b10144f7 [file] [log] [blame]
crazybobleeabc4dd02007-02-01 01:44:36 +00001/**
2 * Copyright (C) 2006 Google Inc.
3 *
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
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
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.
15 */
crazyboblee63b592b2007-01-25 02:45:24 +000016
17package com.google.inject;
18
19/**
crazyboblee235d0682007-01-31 02:25:21 +000020 * Container scope. Returns one instance per {@link Container}.
crazyboblee63b592b2007-01-25 02:45:24 +000021 *
22 * @author crazybob@google.com (Bob Lee)
23 */
crazyboblee235d0682007-01-31 02:25:21 +000024class ContainerScope implements Scope {
crazyboblee63b592b2007-01-25 02:45:24 +000025
crazyboblee235d0682007-01-31 02:25:21 +000026 static final Scope INSTANCE = new ContainerScope();
crazyboblee63b592b2007-01-25 02:45:24 +000027
crazyboblee235d0682007-01-31 02:25:21 +000028 private ContainerScope() {}
crazyboblee63b592b2007-01-25 02:45:24 +000029
30 public <T> Factory<T> scope(Key<T> key, final Factory<T> creator) {
31 return new Factory<T>() {
32
crazybobleefc9337f2007-01-26 00:51:34 +000033 private volatile T instance;
crazyboblee63b592b2007-01-25 02:45:24 +000034
35 public T get() {
crazybobleefc9337f2007-01-26 00:51:34 +000036 // Double checked locking improves performance and is safe as of Java 5.
37 if (instance == null) {
38 // Use a pretty coarse lock. We don't want to run into deadlocks when
crazyboblee235d0682007-01-31 02:25:21 +000039 // two threads try to load circularly-dependent objects.
crazybobleefc9337f2007-01-26 00:51:34 +000040 // Maybe one of these days we will identify independent graphs of
crazyboblee235d0682007-01-31 02:25:21 +000041 // objects and offer to load them in parallel.
crazybobleefc9337f2007-01-26 00:51:34 +000042 synchronized (Container.class) {
43 if (instance == null) {
44 instance = creator.get();
45 }
crazyboblee63b592b2007-01-25 02:45:24 +000046 }
crazyboblee63b592b2007-01-25 02:45:24 +000047 }
crazybobleefc9337f2007-01-26 00:51:34 +000048 return instance;
crazyboblee63b592b2007-01-25 02:45:24 +000049 }
50
51 public String toString() {
52 return creator.toString();
53 }
54 };
55 }
56}