View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.eclipse.aether.internal.impl;
20  
21  import javax.inject.Inject;
22  import javax.inject.Named;
23  import javax.inject.Singleton;
24  
25  import java.util.ArrayList;
26  import java.util.concurrent.CopyOnWriteArrayList;
27  import java.util.concurrent.atomic.AtomicBoolean;
28  
29  import org.eclipse.aether.MultiRuntimeException;
30  import org.eclipse.aether.impl.RepositorySystemLifecycle;
31  
32  import static java.util.Objects.requireNonNull;
33  
34  /**
35   *
36   */
37  @Singleton
38  @Named
39  public class DefaultRepositorySystemLifecycle implements RepositorySystemLifecycle {
40      private final AtomicBoolean shutdown;
41  
42      private final CopyOnWriteArrayList<Runnable> onSystemEndedHandlers;
43  
44      @Inject
45      public DefaultRepositorySystemLifecycle() {
46          this.shutdown = new AtomicBoolean(false);
47          this.onSystemEndedHandlers = new CopyOnWriteArrayList<>();
48      }
49  
50      @Override
51      public void systemEnded() {
52          if (shutdown.compareAndSet(false, true)) {
53              final ArrayList<Exception> exceptions = new ArrayList<>();
54              for (Runnable onCloseHandler : onSystemEndedHandlers) {
55                  try {
56                      onCloseHandler.run();
57                  } catch (Exception e) {
58                      exceptions.add(e);
59                  }
60              }
61              MultiRuntimeException.mayThrow("system on-close handler failures", exceptions);
62          }
63      }
64  
65      @Override
66      public void addOnSystemEndedHandler(Runnable handler) {
67          requireNonNull(handler, "handler cannot be null");
68          requireNotShutdown();
69          onSystemEndedHandlers.add(0, handler);
70      }
71  
72      private void requireNotShutdown() {
73          if (shutdown.get()) {
74              throw new IllegalStateException("repository system is already shut down");
75          }
76      }
77  }