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