Skip to content

Executes Java lambda in multiple threads and collects their results (useful for testing for thread-safety)

License

Notifications You must be signed in to change notification settings

yegor256/together

Repository files navigation

Runs Java Lambda in Many Threads

EO principles respected here DevOps By Rultor.com We recommend IntelliJ IDEA

mvn PDD status Maven Central Javadoc codecov Hits-of-Code License

With this small Java library you can test your objects for thread safety by doing some manipulations with them in multiple parallel threads. You may read this blog post, in order to understand the motivation for this type of testing better: How I Test My Java Classes for Thread-Safety.

By the way, there are similar libraries for Java, but they are either more complex or less tests-oriented, for example lincheck, ConcurrentUnit, RunsInThreads from cactoos-matchers, or Threads from Cactoos.

First, you add this library to your pom.xml in Maven:

<dependency>
  <groupId>com.yegor256</groupId>
  <artifactId>together</artifactId>
  <version>0.1.0</version>
</dependency>

Then, you use it like this, in your JUnit5 test (with Hamcrest):

import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import com.yegor256.Together;

class FooTest {
  @Test
  void worksAsExpected() {
    MatcherAssert.assertThat(
      "processes all lambdas successfully",
      new Together<>(
        thread -> {
          // Do the job and use "thread" as a number
          // of the thread currently running (they are all unique).
          return true;
        }
      ),
      Matchers.not(Matchers.hasItem(Matchers.is(false)))
    );
  }
}

Here, the Together class will run the "job" in multiple threads and will make sure that all of them return true. If at least one of them returns false, the test will fail. If at least one of the threads will throw an exception, the test will also fail.

Together guarantees that all threads will start exactly simultaneously, thus simulating race condition as much as it's possible. This is exactly what you need for your tests: making sure your object under test experiences troubles that are very similar to what it might experience in real life.

For even better/stronger testing, you can use @RepeatedTest.

How to Contribute

Fork repository, make changes, send us a pull request. We will review your changes and apply them to the master branch shortly, provided they don't violate our quality standards. To avoid frustration, before sending us your pull request please run full Maven build:

mvn clean install -Pqulice

You will need Maven 3.3+ and Java 11+.

About

Executes Java lambda in multiple threads and collects their results (useful for testing for thread-safety)

Topics

Resources

License

Stars

Watchers

Forks

Contributors 3

  •  
  •  
  •  

Languages