View Javadoc

1   /*
2    * Copyright [2007] [University Corporation for Advanced Internet Development, 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   */
16  
17  package org.opensaml.xml.util;
18  
19  import java.util.WeakHashMap;
20  
21  /**
22   * A simple implementation of {@link SingletonFactory}.
23   * 
24   * <p>
25   * A {@link WeakHashMap} is used as the underlying store. This ensures that if the input class 
26   * instance become otherwise unused (weakly reachable), the input class instance key used 
27   * within the factory will not prevent the input class instance from being garbage-collected,
28   * thereby preventing a memory leak.
29   * </p>
30   * 
31   * <p>
32   * <strong>NOTE: </strong>If the output class instance holds a strong or soft reference to the input class,
33   * do not use this factory.  See instead {@link AbstractWrappedSingletonFactory}. Usage of this
34   * class in that scenario will result in a memory leak, as the input class instance will never
35   * become weakly reachable and therefore never garbage collected.
36   * </p>
37   * 
38   *
39   * @param <Input> the factory input class type
40   * @param <Output> the factory output class type
41   */
42  public abstract class AbstractSimpleSingletonFactory<Input, Output> 
43          extends AbstractSingletonFactory<Input, Output> {
44      
45      /** Storage for the factory. */
46      private WeakHashMap<Input, Output> map;
47      
48      /** Constructor. */
49      public AbstractSimpleSingletonFactory() {
50          map = new WeakHashMap<Input, Output>();
51      }
52      
53      /** {@inheritDoc} */
54      protected synchronized Output get(Input input) {
55          return map.get(input);
56      }
57      
58      /** {@inheritDoc} */
59      protected synchronized void put(Input input, Output output) {
60          map.put(input, output);
61      }
62      
63  }