• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2008 The Guava Authors
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 com.google.common.testing;
18 
19 import static com.google.common.base.Preconditions.checkNotNull;
20 
21 import com.google.common.annotations.GwtCompatible;
22 import com.google.common.collect.Lists;
23 import com.google.errorprone.annotations.concurrent.GuardedBy;
24 import java.util.ArrayList;
25 import java.util.LinkedList;
26 import java.util.List;
27 import java.util.logging.Level;
28 import java.util.logging.Logger;
29 
30 /**
31  * A {@code TearDownStack} contains a stack of {@link TearDown} instances.
32  *
33  * <p>This class is thread-safe.
34  *
35  * @author Kevin Bourrillion
36  * @since 10.0
37  */
38 @GwtCompatible
39 @ElementTypesAreNonnullByDefault
40 public class TearDownStack implements TearDownAccepter {
41   private static final Logger logger = Logger.getLogger(TearDownStack.class.getName());
42 
43   @GuardedBy("stack")
44   final LinkedList<TearDown> stack = new LinkedList<>();
45 
46   private final boolean suppressThrows;
47 
TearDownStack()48   public TearDownStack() {
49     this.suppressThrows = false;
50   }
51 
TearDownStack(boolean suppressThrows)52   public TearDownStack(boolean suppressThrows) {
53     this.suppressThrows = suppressThrows;
54   }
55 
56   @Override
addTearDown(TearDown tearDown)57   public final void addTearDown(TearDown tearDown) {
58     synchronized (stack) {
59       stack.addFirst(checkNotNull(tearDown));
60     }
61   }
62 
63   /** Causes teardown to execute. */
runTearDown()64   public final void runTearDown() {
65     List<Throwable> exceptions = new ArrayList<>();
66     List<TearDown> stackCopy;
67     synchronized (stack) {
68       stackCopy = Lists.newArrayList(stack);
69       stack.clear();
70     }
71     for (TearDown tearDown : stackCopy) {
72       try {
73         tearDown.tearDown();
74       } catch (Throwable t) {
75         if (suppressThrows) {
76           logger.log(Level.INFO, "exception thrown during tearDown", t);
77         } else {
78           exceptions.add(t);
79         }
80       }
81     }
82     if (!suppressThrows && (exceptions.size() > 0)) {
83       throw ClusterException.create(exceptions);
84     }
85   }
86 }
87