pax_global_header00006660000000000000000000000064135246511310014513gustar00rootroot0000000000000052 comment=4e3b3ba6f410e390dca929411081dafe3dc16d9c concurrentunit-concurrentunit-0.4.6/000077500000000000000000000000001352465113100176645ustar00rootroot00000000000000concurrentunit-concurrentunit-0.4.6/.gitignore000066400000000000000000000001111352465113100216450ustar00rootroot00000000000000target/ *~ .project .classpath .settings/ test-output/ docs/ .idea *.iml concurrentunit-concurrentunit-0.4.6/.travis.yml000066400000000000000000000002501352465113100217720ustar00rootroot00000000000000language: java dist: trusty jdk: - oraclejdk8 cache: directories: - .autoconf - "$HOME/.m2" notifications: email: false branches: only: - masterconcurrentunit-concurrentunit-0.4.6/CHANGES.md000066400000000000000000000015671352465113100212670ustar00rootroot00000000000000# 0.4.4 ### New Features * Added OSGi support * Added better TimeoutException error message # 0.4.3 ### Bug Fixes * Fixed issue #17 - ConcurrentUnit.await(long, TimeUnit) not passing through TimeUnit # 0.4.2 ### New Features * Added `Waiter.rethrow` method # 0.4.1 ### Bug Fixes * Waiter no longer checks that `await` calls are made from the main test thread, since JUnit may construct and run the test from different threads # 0.4.0 ### Improvements * Replaced internal usage of thread interrrupts with a circuit * Removed expectResume APIs * Added support for TimeUnits # 0.3.4 ### Bug Fixes * Always reset remaining resumes on interrupt # 0.3.3 ### Bug Fixes * Fixed issue #4 - Use JUnit style argument ordering for for assert equals methods. * Fixed issue #5 - Unit tests passing after single failed test # 0.3.2 ### Changes * Add better failure error messagesconcurrentunit-concurrentunit-0.4.6/LICENSE.txt000066400000000000000000000236751352465113100215240ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONSconcurrentunit-concurrentunit-0.4.6/README.md000066400000000000000000000122731352465113100211500ustar00rootroot00000000000000# ConcurrentUnit [![Build Status](https://travis-ci.org/jhalterman/concurrentunit.svg)](https://travis-ci.org/jhalterman/concurrentunit) [![Maven Central](https://maven-badges.herokuapp.com/maven-central/net.jodah/concurrentunit/badge.svg)](https://maven-badges.herokuapp.com/maven-central/net.jodah/concurrentunit) [![License](http://img.shields.io/:license-apache-brightgreen.svg)](http://www.apache.org/licenses/LICENSE-2.0.html) [![JavaDoc](http://javadoc-badge.appspot.com/net.jodah/concurrentunit.svg?label=javadoc)](https://jhalterman.github.com/concurrentunit/javadoc) A simple, zero-dependency toolkit for testing multi-threaded code. Supports Java 1.6+. ## Introduction ConcurrentUnit was created to help developers test multi-threaded or asynchronous code. It allows you to perform assertions and wait for operations in any thread, with failures being properly reported back to the main test thread. If an assertion fails, your test fails, regardless of which thread the assertion came from. ## Usage 1. Create a `Waiter` 2. Use `Waiter.await` to block the main test thread. 3. Use the `Waiter.assert` calls from any thread to perform assertions. 4. Once expected assertions are completed, use `Waiter.resume` call to unblock the `await`ing thread. When your test runs, assertion failures will result in the main thread being interrupted and the failure thrown. If an `await` call times out before all expected `resume` calls occur, the test will fail with a `TimeoutException`. ## Examples Consider a test for a message bus that delivers messages asynchronously: ```java @Test public void shouldDeliverMessage() throws Throwable { final Waiter waiter = new Waiter(); messageBus.registerHandler(message -> { // Called on separate thread waiter.assertEquals(message, "foo"); waiter.resume(); }; messageBus.send("foo"); // Wait for resume() to be called waiter.await(1000); } ``` We can also handle wait for multiple `resume` calls: ```java @Test public void shouldDeliverMessages() throws Throwable { final Waiter waiter = new Waiter(); messageBus.registerHandler(message -> { waiter.assertEquals(message, "foo"); waiter.resume(); }; messageBus.send("foo"); messageBus.send("foo"); messageBus.send("foo"); // Wait for resume() to be called 3 times waiter.await(1000, 3); } ``` If an assertion fails in any thread, the test will fail as expected: ```java @Test(expected = AssertionError.class) public void shouldFail() throws Throwable { final Waiter waiter = new Waiter(); new Thread(() -> { waiter.assertTrue(false); }).start(); waiter.await(); } ``` TimeoutException is thrown if `resume` is not called before the `await` time is exceeded: ```java @Test(expected = TimeoutException.class) public void shouldTimeout() throws Throwable { new Waiter().await(1); } ``` #### Alternatively As a more concise alternative to using the `Waiter` class, you can extend the `ConcurrentTestCase`: ```java class SomeTest extends ConcurrentTestCase { @Test public void shouldSucceed() throws Throwable { new Thread(() -> { doSomeWork(); threadAssertTrue(true); resume(); }).start(); await(1000); } } ``` #### Assertions ConcurrentUnit's `Waiter` supports the standard assertions along with [Hamcrest Matcher](http://hamcrest.org/JavaHamcrest/javadoc/) assertions: ```java waiter.assertEquals(expected, result); waiter.assertThat(result, is(equalTo(expected))); ``` Since Hamcrest is an optional dependency, users need to explicitly add it to their classpath (via Maven/Gradle/etc). #### Other Examples More example usages can be found in the [WaiterTest](https://github.com/jhalterman/concurrentunit/blob/master/src/test/java/net/jodah/concurrentunit/WaiterTest.java) or in the following projects: * [Atomix](https://github.com/atomix/atomix/tree/master/core/src/test/java/io/atomix) * [Copycat](https://github.com/atomix/copycat/tree/master/server/src/test/java/io/atomix/copycat/server/state) * [Failsafe](https://github.com/jhalterman/failsafe/blob/master/src/test/java/net/jodah/failsafe/AsyncFailsafeTest.java) * [ExpiringMap](https://github.com/jhalterman/expiringmap/tree/master/src/test/java/net/jodah/expiringmap/functional) * [Lyra](https://github.com/jhalterman/lyra/tree/master/src/test/java/net/jodah/lyra/internal/util/concurrent) ## Additional Notes #### On `await` / `resume` Timing Since it is not always possible to ensure that `resume` is called after `await` in multi-threaded tests, ConcurrentUnit allows them to be called in either order. If `resume` is called before `await`, the resume calls are recorded and `await` will return immediately if the expected number of resumes have already occurred. This ability comes with a caveat though: it is not possible to detect when additional unexpected `resume` calls are made since ConcurrentUnit allows an `await` call to follow. ## Additional Resources - [Javadocs](https://jodah.net/concurrentunit/javadoc) - [An article](https://jodah.net/testing-multi-threaded-code) describing the motivation for ConcurrentUnit ## License Copyright 2011-2016 Jonathan Halterman - Released under the [Apache 2.0 license](http://www.apache.org/licenses/LICENSE-2.0.html). concurrentunit-concurrentunit-0.4.6/bin/000077500000000000000000000000001352465113100204345ustar00rootroot00000000000000concurrentunit-concurrentunit-0.4.6/bin/push-javadoc.sh000077500000000000000000000006121352465113100233560ustar00rootroot00000000000000#!/bin/sh # run from top level dir PROJECT=concurrentunit mvn javadoc:javadoc -Djv=$apiVersion rm -rf target/docs git clone git@github.com:jhalterman/$PROJECT.git target/docs -b gh-pages cd target/docs git rm -rf javadoc mkdir -p javadoc mv -v ../site/apidocs/* javadoc git add -A -f javadoc git commit -m "Updated JavaDocs" git push -fq origin gh-pages > /dev/null echo "Published JavaDocs"concurrentunit-concurrentunit-0.4.6/pom.xml000066400000000000000000000120711352465113100212020ustar00rootroot00000000000000 4.0.0 org.sonatype.oss oss-parent 7 net.jodah concurrentunit 0.4.6 ConcurrentUnit https://github.com/jhalterman/concurrentunit 2010 bundle Toolkit for testing multi-threaded and asynchronous applications Apache License, Version 2.0 http://apache.org/licenses/LICENSE-2.0 repo Jonathan Halterman http://jodah.net scm:git:git@github.com:jhalterman/concurrentunit.git scm:git:git@github.com:jhalterman/concurrentunit.git http://github.com/jhalterman/concurrentunit/ org.apache.maven.plugins maven-compiler-plugin 1.6 1.6 maven-release-plugin release -Prelease org.apache.maven.plugins maven-javadoc-plugin 2.10.4 attach-javadocs jar false protected *.internal -Xdoclint:none -notimestamp -link http://docs.oracle.com/javase/8/docs/api/ org.apache.felix maven-bundle-plugin 3.5.1 true net.jodah.concurrentunit.* * org.testng testng 6.5.2 test org.hamcrest hamcrest-all 1.3 true release org.apache.maven.plugins maven-source-plugin 2.1.2 attach-sources jar-no-fork org.apache.maven.plugins maven-gpg-plugin 1.1 sign-artifacts verify sign org.sonatype.plugins nexus-staging-maven-plugin 1.6.7 true sonatype-nexus-staging https://oss.sonatype.org/ true org.apache.maven.plugins maven-release-plugin deploy nexus-staging:release concurrentunit-concurrentunit-0.4.6/src/000077500000000000000000000000001352465113100204535ustar00rootroot00000000000000concurrentunit-concurrentunit-0.4.6/src/main/000077500000000000000000000000001352465113100213775ustar00rootroot00000000000000concurrentunit-concurrentunit-0.4.6/src/main/java/000077500000000000000000000000001352465113100223205ustar00rootroot00000000000000concurrentunit-concurrentunit-0.4.6/src/main/java/net/000077500000000000000000000000001352465113100231065ustar00rootroot00000000000000concurrentunit-concurrentunit-0.4.6/src/main/java/net/jodah/000077500000000000000000000000001352465113100241735ustar00rootroot00000000000000concurrentunit-concurrentunit-0.4.6/src/main/java/net/jodah/concurrentunit/000077500000000000000000000000001352465113100272555ustar00rootroot00000000000000concurrentunit-concurrentunit-0.4.6/src/main/java/net/jodah/concurrentunit/ConcurrentTestCase.java000066400000000000000000000060361352465113100337030ustar00rootroot00000000000000/* * Copyright 2010-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package net.jodah.concurrentunit; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * Convenience support class, wrapping a {@link Waiter}. * * @author Jonathan Halterman */ public abstract class ConcurrentTestCase { private final Waiter waiter = new Waiter(); /** * @see Waiter#assertEquals(Object, Object) */ public void threadAssertEquals(Object expected, Object actual) { waiter.assertEquals(expected, actual); } /** * @see Waiter#assertTrue(boolean) */ public void threadAssertFalse(boolean b) { waiter.assertFalse(b); } /** * @see Waiter#assertNotNull(Object) */ public void threadAssertNotNull(Object object) { waiter.assertNotNull(object); } /** * @see Waiter#assertNull(Object) */ public void threadAssertNull(Object x) { waiter.assertNull(x); } /** * @see Waiter#assertTrue(boolean) */ public void threadAssertTrue(boolean b) { waiter.assertTrue(b); } /** * @see Waiter#fail() */ public void threadFail() { threadFail(new AssertionError()); } /** * @see Waiter#fail(String) */ public void threadFail(String reason) { threadFail(new AssertionError(reason)); } /** * @see Waiter#fail(Throwable) */ public void threadFail(Throwable reason) { waiter.fail(reason); } /** * @see Waiter#rethrow(Throwable) */ public void rethrow(Throwable reason) { waiter.rethrow(reason); } /** * @see Waiter#await() */ protected void await() throws TimeoutException, InterruptedException { waiter.await(); } /** * @see Waiter#await(long) */ protected void await(long delay) throws TimeoutException, InterruptedException { waiter.await(delay); } /** * @see Waiter#await(long, int) */ protected void await(long delay, int expectedResumes) throws TimeoutException, InterruptedException { waiter.await(delay, expectedResumes); } /** * @see Waiter#await(long, TimeUnit) */ protected void await(long delay, TimeUnit timeUnit) throws TimeoutException, InterruptedException { waiter.await(delay, timeUnit); } /** * @see Waiter#await(long, TimeUnit, int) */ protected void await(long delay, TimeUnit timeUnit, int expectedResumes) throws TimeoutException, InterruptedException { waiter.await(delay, timeUnit, expectedResumes); } /** * @see Waiter#resume() */ protected void resume() { waiter.resume(); } } concurrentunit-concurrentunit-0.4.6/src/main/java/net/jodah/concurrentunit/Waiter.java000066400000000000000000000204061352465113100313550ustar00rootroot00000000000000/* * Copyright 2010-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package net.jodah.concurrentunit; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import net.jodah.concurrentunit.internal.ReentrantCircuit; /** * Waits on a test, carrying out assertions, until being resumed. * * @author Jonathan Halterman */ public class Waiter { private static final String TIMEOUT_MESSAGE = "Test timed out while waiting for an expected result, expectedResumes: %d, actualResumes: %d"; private AtomicInteger remainingResumes = new AtomicInteger(0); private final ReentrantCircuit circuit = new ReentrantCircuit(); private volatile Throwable failure; /** * Creates a new Waiter. */ public Waiter() { circuit.open(); } /** * Asserts that the {@code expected} values equals the {@code actual} value * * @throws AssertionError when the assertion fails */ public void assertEquals(Object expected, Object actual) { if (expected == null && actual == null) return; if (expected != null && expected.equals(actual)) return; fail(format(expected, actual)); } /** * Asserts that the {@code condition} is false. * * @throws AssertionError when the assertion fails */ public void assertFalse(boolean condition) { if (condition) fail("expected false"); } /** * Asserts that the {@code object} is not null. * * @throws AssertionError when the assertion fails */ public void assertNotNull(Object object) { if (object == null) fail("expected not null"); } /** * Asserts that the {@code object} is null. * * @throws AssertionError when the assertion fails */ public void assertNull(Object object) { if (object != null) fail(format("null", object)); } /** * Asserts that the {@code condition} is true. * * @throws AssertionError when the assertion fails */ public void assertTrue(boolean condition) { if (!condition) fail("expected true"); } /** * Asserts that {@code actual} satisfies the condition specified by {@code matcher}. * * @throws AssertionError when the assertion fails */ public void assertThat(T actual, org.hamcrest.Matcher matcher) { try { org.hamcrest.MatcherAssert.assertThat(actual, matcher); } catch (AssertionError e) { fail(e); } } /** * Waits until {@link #resume()} is called, or the test is failed. * * @throws TimeoutException if the operation times out while waiting * @throws InterruptedException if the operations is interrupted while waiting * @throws AssertionError if any assertion fails while waiting */ public void await() throws TimeoutException, InterruptedException { await(0, TimeUnit.MILLISECONDS, 1); } /** * Waits until the {@code delay} has elapsed, {@link #resume()} is called, or the test is failed. * * @param delay Delay to wait in milliseconds * @throws TimeoutException if the operation times out while waiting * @throws InterruptedException if the operations is interrupted while waiting * @throws AssertionError if any assertion fails while waiting */ public void await(long delay) throws TimeoutException, InterruptedException { await(delay, TimeUnit.MILLISECONDS, 1); } /** * Waits until the {@code delay} has elapsed, {@link #resume()} is called, or the test is failed. * * @param delay Delay to wait for * @param timeUnit TimeUnit to delay for * @throws TimeoutException if the operation times out while waiting * @throws InterruptedException if the operations is interrupted while waiting * @throws AssertionError if any assertion fails while waiting */ public void await(long delay, TimeUnit timeUnit) throws TimeoutException, InterruptedException { await(delay, timeUnit, 1); } /** * Waits until the {@code delay} has elapsed, {@link #resume()} is called {@code expectedResumes} times, or the test * is failed. * * @param delay Delay to wait for in milliseconds * @param expectedResumes Number of times {@link #resume()} is expected to be called before the awaiting thread is * resumed * @throws TimeoutException if the operation times out while waiting * @throws InterruptedException if the operations is interrupted while waiting * @throws AssertionError if any assertion fails while waiting */ public void await(long delay, int expectedResumes) throws TimeoutException, InterruptedException { await(delay, TimeUnit.MILLISECONDS, expectedResumes); } /** * Waits until the {@code delay} has elapsed, {@link #resume()} is called {@code expectedResumes} times, or the test * is failed. * * @param delay Delay to wait for * @param timeUnit TimeUnit to delay for * @param expectedResumes Number of times {@link #resume()} is expected to be called before the awaiting thread is * resumed * @throws TimeoutException if the operation times out while waiting * @throws InterruptedException if the operations is interrupted while waiting * @throws AssertionError if any assertion fails while waiting */ public void await(long delay, TimeUnit timeUnit, int expectedResumes) throws TimeoutException, InterruptedException { try { if (failure == null) { synchronized (this) { int remaining = remainingResumes.addAndGet(expectedResumes); if (remaining > 0) circuit.open(); } if (delay == 0) circuit.await(); else if (!circuit.await(delay, timeUnit)) { final int actualResumes = expectedResumes - remainingResumes.get(); throw new TimeoutException(String.format(TIMEOUT_MESSAGE, expectedResumes, actualResumes)); } } } finally { remainingResumes.set(0); circuit.open(); if (failure != null) { Throwable f = failure; failure = null; sneakyThrow(f); } } } /** * Resumes the waiter when the expected number of {@link #resume()} calls have occurred. */ public synchronized void resume() { if (remainingResumes.decrementAndGet() <= 0) circuit.close(); } /** * Fails the current test. * * @throws AssertionError */ public void fail() { fail(new AssertionError()); } /** * Fails the current test for the given {@code reason}. * * @throws AssertionError */ public void fail(String reason) { fail(new AssertionError(reason)); } /** * Fails the current test with the given {@code reason}, sets the number of expected resumes to 0, and throws the * {@code reason} as an {@code AssertionError} in the main test thread and in the current thread. * * @throws AssertionError wrapping the {@code reason} */ public void fail(Throwable reason) { AssertionError ae = null; if (reason instanceof AssertionError) ae = (AssertionError) reason; else { ae = new AssertionError(); ae.initCause(reason); } failure = ae; circuit.close(); throw ae; } /** * Rethrows the {@code failure} in the main test thread and in the current thread. Differs from * {@link #fail(Throwable)} which wraps a failure in an AssertionError before throwing. * * @throws Throwable the {@code failure} */ public void rethrow(Throwable failure) { this.failure = failure; circuit.close(); sneakyThrow(failure); } private static void sneakyThrow(Throwable t) { Waiter.sneakyThrow2(t); } @SuppressWarnings("unchecked") private static void sneakyThrow2(Throwable t) throws T { throw (T) t; } private String format(Object expected, Object actual) { return "expected:<" + expected + "> but was:<" + actual + ">"; } } concurrentunit-concurrentunit-0.4.6/src/main/java/net/jodah/concurrentunit/internal/000077500000000000000000000000001352465113100310715ustar00rootroot00000000000000ReentrantCircuit.java000066400000000000000000000061161352465113100351460ustar00rootroot00000000000000concurrentunit-concurrentunit-0.4.6/src/main/java/net/jodah/concurrentunit/internal/* * Copyright 2010-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package net.jodah.concurrentunit.internal; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.AbstractQueuedSynchronizer; /** * A circuit that accepts re-entrant {@link #open()} and {@link #close()} calls, allows waiting * threads to be interrupted, and ensures fairness when releasing {@link #await() waiting} threads. * * @author Jonathan Halterman */ public class ReentrantCircuit { private final Sync sync = new Sync(); /** * Synchronization state of 0 = closed, 1 = open. */ private static final class Sync extends AbstractQueuedSynchronizer { private static final long serialVersionUID = 992522674231731445L; /** * Closes the circuit. */ @Override public boolean tryReleaseShared(int ignored) { setState(0); return true; } /** * Opens the circuit if not a test. */ @Override protected int tryAcquireShared(int acquires) { // Check to make sure the acquisition is not barging in front of a queued thread Thread queuedThread = getFirstQueuedThread(); if (queuedThread != null && queuedThread != Thread.currentThread()) return -1; // If await test if (acquires == 0) return isClosed() ? 1 : -1; // Explicit open call setState(1); return 1; } private boolean isClosed() { return getState() == 0; } private void open() { setState(1); } } /** * Waits for the circuit to be closed, aborting if interrupted. */ public void await() throws InterruptedException { sync.acquireSharedInterruptibly(0); } /** * Waits for the {@code waitDuration} until the circuit has been closed, aborting if interrupted, * returning true if the circuit is closed else false. */ public boolean await(long waitDuration, TimeUnit timeUnit) throws InterruptedException { return sync.tryAcquireSharedNanos(0, timeUnit.toNanos(waitDuration)); } /** * Closes the circuit, releasing any waiting threads. */ public void close() { sync.releaseShared(1); } /** * Interrupts waiting threads. */ public void interruptWaiters() { for (Thread t : sync.getSharedQueuedThreads()) t.interrupt(); } /** * Returns whether the circuit is closed. */ public boolean isClosed() { return sync.isClosed(); } /** * Opens the circuit. */ public void open() { sync.open(); } @Override public String toString() { return isClosed() ? "closed" : "open"; } } concurrentunit-concurrentunit-0.4.6/src/test/000077500000000000000000000000001352465113100214325ustar00rootroot00000000000000concurrentunit-concurrentunit-0.4.6/src/test/java/000077500000000000000000000000001352465113100223535ustar00rootroot00000000000000concurrentunit-concurrentunit-0.4.6/src/test/java/net/000077500000000000000000000000001352465113100231415ustar00rootroot00000000000000concurrentunit-concurrentunit-0.4.6/src/test/java/net/jodah/000077500000000000000000000000001352465113100242265ustar00rootroot00000000000000concurrentunit-concurrentunit-0.4.6/src/test/java/net/jodah/concurrentunit/000077500000000000000000000000001352465113100273105ustar00rootroot00000000000000concurrentunit-concurrentunit-0.4.6/src/test/java/net/jodah/concurrentunit/WaiterTest.java000066400000000000000000000130641352465113100322520ustar00rootroot00000000000000package net.jodah.concurrentunit; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import java.io.IOException; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import org.testng.annotations.Test; /** * Tests {@link Waiter}. */ @Test public class WaiterTest { @Test public void shouldSupportMultipleThreads() throws Throwable { final Waiter waiter = new Waiter(); for (int i = 0; i < 5; i++) new Thread(new Runnable() { public void run() { waiter.assertTrue(true); waiter.resume(); } }).start(); waiter.await(0); } /** * Should support resume. */ public void waitShouldSupportResume() throws Throwable { final Waiter w = new Waiter(); new Thread(new Runnable() { public void run() { w.resume(); } }).start(); w.await(); } /** * Should throw an assertion error caused by the failure. */ public void waitShouldSupportFail() throws Throwable { final Waiter w = new Waiter(); new Thread(new Runnable() { public void run() { w.fail(new IllegalArgumentException()); } }).start(); try { w.await(); fail(); } catch (AssertionError e) { assertTrue(e.getCause() instanceof IllegalArgumentException); } } /** * Should throw an assertion error. */ @Test(expectedExceptions = AssertionError.class) public void waitShouldSupportAssertionErrors() throws Throwable { final Waiter w = new Waiter(); new Thread(new Runnable() { public void run() { w.assertTrue(false); } }).start(); w.await(); } /** * Should timeout. */ @Test(expectedExceptions = TimeoutException.class) public void waitShouldSupportTimeouts() throws Throwable { final Waiter w = new Waiter(); w.await(10); } /** * Ensures that waiting for multiple resumes works as expected. */ public void shouldSupportMultipleResumes() throws Throwable { final Waiter w = new Waiter(); new Thread(new Runnable() { public void run() { for (int i = 0; i < 5; i++) w.resume(); } }).start(); w.await(500, 5); } public void shouldSupportThreadWait0WithResumeCount() throws Throwable { final Waiter w = new Waiter(); new Thread(new Runnable() { public void run() { for (int i = 0; i < 5; i++) w.resume(); } }).start(); w.await(0, 5); } @Test(expectedExceptions = AssertionError.class) public void shouldFailNullAssertionWithReason() throws Throwable { Waiter w = new Waiter(); w.assertNull("test"); } @Test(expectedExceptions = AssertionError.class) public void shouldFailNullAssertionFromWorkerThreadWithReason() throws Throwable { final Waiter w = new Waiter(); new Thread(new Runnable() { public void run() { w.assertNull("test"); } }).start(); w.await(); } public void shouldHandleResumesThenAwait() throws Throwable { final Waiter w = new Waiter(); final AtomicInteger expectedResumes = new AtomicInteger(); new Thread(new Runnable() { public void run() { try { w.resume(); expectedResumes.incrementAndGet(); Thread.sleep(400); expectedResumes.incrementAndGet(); w.resume(); } catch (InterruptedException e) { } } }).start(); Thread.sleep(200); w.await(0, 2); assertEquals(expectedResumes.get(), 2, "Expected two resumes from separate thread"); } @Test(expectedExceptions = AssertionError.class) public void shouldHandleFailThenAwait() throws Throwable { final Waiter w = new Waiter(); new Thread(new Runnable() { public void run() { w.fail(); } }).start(); Thread.sleep(400); w.await(0, 5); } @Test(expectedExceptions = AssertionError.class) public void shouldHandleResumeFailAwait() throws Throwable { final Waiter w = new Waiter(); new Thread(new Runnable() { public void run() { try { w.resume(); w.fail(); } catch (Throwable ignore) { } } }).start(); Thread.sleep(400); w.await(); } @Test(expectedExceptions = AssertionError.class) public void shouldHandleFailResumeAwait() throws Throwable { final Waiter w = new Waiter(); new Thread(new Runnable() { public void run() { try { w.fail(); } catch (Throwable ignore) { } w.resume(); } }).start(); Thread.sleep(400); w.await(); } @Test(expectedExceptions = IOException.class) public void shouldRethrow() throws Throwable { final Waiter w = new Waiter(); new Thread(new Runnable() { public void run() { w.rethrow(new IOException()); } }).start(); w.await(); } @Test(expectedExceptions = InterruptedException.class) public void shouldHandleInterruption() throws Throwable { final Waiter w = new Waiter(); final Thread main = Thread.currentThread(); new Thread(new Runnable() { public void run() { main.interrupt(); } }).start(); w.await(1000); } public void shouldSupportSuccessiveResumeAwaits() throws Throwable { final Waiter w = new Waiter(); w.resume(); w.await(); w.resume(); w.await(); } public void shouldSupportSuccessiveResumes() throws Throwable { final Waiter w = new Waiter(); w.resume(); w.resume(); w.resume(); w.await(); } } concurrentunit-concurrentunit-0.4.6/src/test/java/net/jodah/concurrentunit/internal/000077500000000000000000000000001352465113100311245ustar00rootroot00000000000000ReentrantCircuitTest.java000066400000000000000000000062161352465113100360420ustar00rootroot00000000000000concurrentunit-concurrentunit-0.4.6/src/test/java/net/jodah/concurrentunit/internalpackage net.jodah.concurrentunit.internal; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import java.util.concurrent.TimeUnit; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import net.jodah.concurrentunit.Waiter; @Test public class ReentrantCircuitTest { ReentrantCircuit circuit; @BeforeMethod protected void beforeMethod() { circuit = new ReentrantCircuit(); } public void shouldInitiallyBeClosed() { assertTrue(circuit.isClosed()); } public void shouldHandleOpenCloseCycles() { for (int i = 0; i < 3; i++) { circuit.open(); circuit.close(); } assertTrue(circuit.isClosed()); } public void shouldHandleRepeatedOpens() { for (int i = 0; i < 3; i++) circuit.open(); assertFalse(circuit.isClosed()); } public void shouldHandleRepeatedClosed() { for (int i = 0; i < 3; i++) circuit.close(); assertTrue(circuit.isClosed()); } public void shouldReturnWhenAwaitAndAlreadyClosed() throws Throwable { long t = System.currentTimeMillis(); circuit.await(); circuit.await(3, TimeUnit.MINUTES); // Awaits should return immediately assertTrue(System.currentTimeMillis() - t < 500); } public void shouldHandleSequentialWaiters() throws Throwable { final Waiter waiter = new Waiter(); for (int i = 0; i < 1; i++) { circuit.open(); new Thread(new Runnable() { @Override public void run() { try { circuit.await(); waiter.resume(); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); Thread.sleep(500); circuit.close(); waiter.await(500); } } public void shouldHandleConcurrentWaiters() throws Throwable { circuit.open(); final Waiter waiter = new Waiter(); for (int i = 0; i < 3; i++) new Thread(new Runnable() { @Override public void run() { try { circuit.await(); waiter.resume(); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); Thread.sleep(1000); circuit.close(); waiter.await(500); } public void shouldInterruptWaiters() throws Throwable { circuit.open(); final Waiter waiter = new Waiter(); for (int i = 0; i < 3; i++) new Thread(new Runnable() { @Override public void run() { try { circuit.await(); } catch (InterruptedException e) { waiter.resume(); } } }).start(); Thread.sleep(300); circuit.interruptWaiters(); waiter.await(500); } public void shouldNotBlockOpenWhenSyncAcquired() throws Throwable { circuit.open(); final Waiter waiter = new Waiter(); new Thread(new Runnable() { @Override public void run() { try { circuit.await(); waiter.resume(); } catch (InterruptedException e) { } } }).start(); Thread.sleep(300); circuit.open(); circuit.close(); waiter.await(500); } } concurrentunit-concurrentunit-0.4.6/src/test/java/net/jodah/concurrentunit/issues/000077500000000000000000000000001352465113100306235ustar00rootroot00000000000000concurrentunit-concurrentunit-0.4.6/src/test/java/net/jodah/concurrentunit/issues/Issue5.java000066400000000000000000000013131352465113100326410ustar00rootroot00000000000000package net.jodah.concurrentunit.issues; import net.jodah.concurrentunit.Waiter; import org.testng.annotations.Test; /** * https://github.com/jhalterman/concurrentunit/issues/5 */ @Test public class Issue5 { @Test(expectedExceptions = AssertionError.class) public void testOne() throws Throwable { performTest(); } @Test(expectedExceptions = AssertionError.class) public void testTwo() throws Throwable { performTest(); } void performTest() throws Throwable { final Waiter waiter = new Waiter(); new Thread(new Runnable() { @Override public void run() { waiter.assertTrue(false); waiter.resume(); } }).start(); waiter.await(100); } }