pax_global_header 0000666 0000000 0000000 00000000064 13524651131 0014513 g ustar 00root root 0000000 0000000 52 comment=4e3b3ba6f410e390dca929411081dafe3dc16d9c
concurrentunit-concurrentunit-0.4.6/ 0000775 0000000 0000000 00000000000 13524651131 0017664 5 ustar 00root root 0000000 0000000 concurrentunit-concurrentunit-0.4.6/.gitignore 0000664 0000000 0000000 00000000111 13524651131 0021645 0 ustar 00root root 0000000 0000000 target/
*~
.project
.classpath
.settings/
test-output/
docs/
.idea
*.iml
concurrentunit-concurrentunit-0.4.6/.travis.yml 0000664 0000000 0000000 00000000250 13524651131 0021772 0 ustar 00root root 0000000 0000000 language: java
dist: trusty
jdk:
- oraclejdk8
cache:
directories:
- .autoconf
- "$HOME/.m2"
notifications:
email: false
branches:
only:
- master concurrentunit-concurrentunit-0.4.6/CHANGES.md 0000664 0000000 0000000 00000001567 13524651131 0021267 0 ustar 00root root 0000000 0000000 # 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 messages concurrentunit-concurrentunit-0.4.6/LICENSE.txt 0000664 0000000 0000000 00000023675 13524651131 0021524 0 ustar 00root root 0000000 0000000
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 CONDITIONS concurrentunit-concurrentunit-0.4.6/README.md 0000664 0000000 0000000 00000012273 13524651131 0021150 0 ustar 00root root 0000000 0000000 # ConcurrentUnit
[](https://travis-ci.org/jhalterman/concurrentunit)
[](https://maven-badges.herokuapp.com/maven-central/net.jodah/concurrentunit)
[](http://www.apache.org/licenses/LICENSE-2.0.html)
[](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/ 0000775 0000000 0000000 00000000000 13524651131 0020434 5 ustar 00root root 0000000 0000000 concurrentunit-concurrentunit-0.4.6/bin/push-javadoc.sh 0000775 0000000 0000000 00000000612 13524651131 0023356 0 ustar 00root root 0000000 0000000 #!/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.xml 0000664 0000000 0000000 00000012071 13524651131 0021202 0 ustar 00root root 0000000 0000000 4.0.0org.sonatype.ossoss-parent7net.jodahconcurrentunit0.4.6ConcurrentUnithttps://github.com/jhalterman/concurrentunit2010bundleToolkit for testing multi-threaded and asynchronous applicationsApache License, Version 2.0http://apache.org/licenses/LICENSE-2.0repoJonathan Haltermanhttp://jodah.netscm:git:git@github.com:jhalterman/concurrentunit.gitscm:git:git@github.com:jhalterman/concurrentunit.githttp://github.com/jhalterman/concurrentunit/org.apache.maven.pluginsmaven-compiler-plugin1.61.6maven-release-pluginrelease-Preleaseorg.apache.maven.pluginsmaven-javadoc-plugin2.10.4attach-javadocsjarfalseprotected*.internal
-Xdoclint:none
-notimestamp
-link http://docs.oracle.com/javase/8/docs/api/
org.apache.felixmaven-bundle-plugin3.5.1truenet.jodah.concurrentunit.**org.testngtestng6.5.2testorg.hamcresthamcrest-all1.3truereleaseorg.apache.maven.pluginsmaven-source-plugin2.1.2attach-sourcesjar-no-forkorg.apache.maven.pluginsmaven-gpg-plugin1.1sign-artifactsverifysignorg.sonatype.pluginsnexus-staging-maven-plugin1.6.7truesonatype-nexus-staginghttps://oss.sonatype.org/trueorg.apache.maven.pluginsmaven-release-plugindeploy nexus-staging:release
concurrentunit-concurrentunit-0.4.6/src/ 0000775 0000000 0000000 00000000000 13524651131 0020453 5 ustar 00root root 0000000 0000000 concurrentunit-concurrentunit-0.4.6/src/main/ 0000775 0000000 0000000 00000000000 13524651131 0021377 5 ustar 00root root 0000000 0000000 concurrentunit-concurrentunit-0.4.6/src/main/java/ 0000775 0000000 0000000 00000000000 13524651131 0022320 5 ustar 00root root 0000000 0000000 concurrentunit-concurrentunit-0.4.6/src/main/java/net/ 0000775 0000000 0000000 00000000000 13524651131 0023106 5 ustar 00root root 0000000 0000000 concurrentunit-concurrentunit-0.4.6/src/main/java/net/jodah/ 0000775 0000000 0000000 00000000000 13524651131 0024173 5 ustar 00root root 0000000 0000000 concurrentunit-concurrentunit-0.4.6/src/main/java/net/jodah/concurrentunit/ 0000775 0000000 0000000 00000000000 13524651131 0027255 5 ustar 00root root 0000000 0000000 concurrentunit-concurrentunit-0.4.6/src/main/java/net/jodah/concurrentunit/ConcurrentTestCase.java 0000664 0000000 0000000 00000006036 13524651131 0033703 0 ustar 00root root 0000000 0000000 /*
* 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.java 0000664 0000000 0000000 00000020406 13524651131 0031355 0 ustar 00root root 0000000 0000000 /*
* 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 super T> 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/ 0000775 0000000 0000000 00000000000 13524651131 0031071 5 ustar 00root root 0000000 0000000 ReentrantCircuit.java 0000664 0000000 0000000 00000006116 13524651131 0035146 0 ustar 00root root 0000000 0000000 concurrentunit-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/ 0000775 0000000 0000000 00000000000 13524651131 0021432 5 ustar 00root root 0000000 0000000 concurrentunit-concurrentunit-0.4.6/src/test/java/ 0000775 0000000 0000000 00000000000 13524651131 0022353 5 ustar 00root root 0000000 0000000 concurrentunit-concurrentunit-0.4.6/src/test/java/net/ 0000775 0000000 0000000 00000000000 13524651131 0023141 5 ustar 00root root 0000000 0000000 concurrentunit-concurrentunit-0.4.6/src/test/java/net/jodah/ 0000775 0000000 0000000 00000000000 13524651131 0024226 5 ustar 00root root 0000000 0000000 concurrentunit-concurrentunit-0.4.6/src/test/java/net/jodah/concurrentunit/ 0000775 0000000 0000000 00000000000 13524651131 0027310 5 ustar 00root root 0000000 0000000 concurrentunit-concurrentunit-0.4.6/src/test/java/net/jodah/concurrentunit/WaiterTest.java 0000664 0000000 0000000 00000013064 13524651131 0032252 0 ustar 00root root 0000000 0000000 package 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/ 0000775 0000000 0000000 00000000000 13524651131 0031124 5 ustar 00root root 0000000 0000000 ReentrantCircuitTest.java 0000664 0000000 0000000 00000006216 13524651131 0036042 0 ustar 00root root 0000000 0000000 concurrentunit-concurrentunit-0.4.6/src/test/java/net/jodah/concurrentunit/internal package 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/ 0000775 0000000 0000000 00000000000 13524651131 0030623 5 ustar 00root root 0000000 0000000 concurrentunit-concurrentunit-0.4.6/src/test/java/net/jodah/concurrentunit/issues/Issue5.java 0000664 0000000 0000000 00000001313 13524651131 0032641 0 ustar 00root root 0000000 0000000 package 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);
}
}