View Javadoc
1   package org.codehaus.plexus.component.manager;
2   
3   /*
4    * Copyright 2001-2006 Codehaus Foundation.
5    * 
6    * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
7    * in compliance with the License. You may obtain a copy of the License at
8    * 
9    * http://www.apache.org/licenses/LICENSE-2.0
10   * 
11   * Unless required by applicable law or agreed to in writing, software distributed under the License
12   * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
13   * or implied. See the License for the specific language governing permissions and limitations under
14   * the License.
15   */
16  
17  import org.codehaus.plexus.component.factory.ComponentInstantiationException;
18  import org.codehaus.plexus.component.repository.exception.ComponentLifecycleException;
19  import org.codehaus.plexus.component.repository.ComponentDescriptor;
20  import org.codehaus.plexus.MutablePlexusContainer;
21  import org.codehaus.plexus.lifecycle.LifecycleHandler;
22  
23  /**
24   * This ensures a component is only used as a singleton, and is only shutdown when the container
25   * shuts down.
26   * 
27   * @author Jason van Zyl
28   */
29  public class SingletonComponentManager<T>
30      extends AbstractComponentManager<T>
31  {
32      private T singleton;
33  
34      public SingletonComponentManager( MutablePlexusContainer container,
35                                        LifecycleHandler lifecycleHandler,
36                                        ComponentDescriptor<T> componentDescriptor,
37                                        String role,
38                                        String roleHint )
39      {
40          super( container, lifecycleHandler, componentDescriptor, role, roleHint );
41      }
42  
43      public synchronized void release( Object component )
44          throws ComponentLifecycleException
45      {
46          if ( singleton == component )
47          {
48              dispose();
49          }
50      }
51  
52      public synchronized void dispose()
53          throws ComponentLifecycleException
54      {
55          if ( singleton != null )
56          {
57              endComponentLifecycle( singleton );
58              singleton = null;
59          }
60      }
61  
62      public synchronized T getComponent( )
63          throws ComponentInstantiationException, ComponentLifecycleException
64      {
65          if ( singleton == null )
66          {
67              singleton = createComponentInstance();
68          }
69  
70          incrementConnectionCount();
71  
72          return singleton;
73      }
74  }