ExceptionHelper { public static <T> boolean addThrowable(AtomicReference<Throwable> field, Throwable exception) { for (;;) { Throwable current = field.get(); if (current == TERMINATED) { return false; } Throwable update; if (current == null) { update = exception; } else { update = new CompositeException(current, exception); } if (field.compareAndSet(current, update)) { return true; } } } private  ExceptionHelper(); static RuntimeException wrapOrThrow(Throwable error); static boolean addThrowable(AtomicReference<Throwable> field, Throwable exception); static Throwable terminate(AtomicReference<Throwable> field); static List<Throwable> flatten(Throwable t); @SuppressWarnings("unchecked") static Exception throwIfThrowable(Throwable e); static final Throwable TERMINATED; }
@Test public void addRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final AtomicReference<Throwable> error = new AtomicReference<Throwable>(); final TestException ex = new TestException(); Runnable r = new Runnable() { @Override public void run() { assertTrue(ExceptionHelper.addThrowable(error, ex)); } }; TestHelper.race(r, r); } }