How it works...

In this recipe, you implemented a test for the LinkedTransferQueue class using the MultithreadedTC library. You can implement a test in any concurrent application or class using this library and its metronome. In the example, you implemented the classical producer/consumer problem with two consumers and a producer. You wanted to test that the first String object introduced in the buffer is consumed by the first consumer that arrives at the buffer, and the second String object introduced in the buffer is consumed by the second consumer that arrives at the buffer.

The MultithreadedTC library is based on the JUnit library, which is the most often used library to implement unit tests in Java. To implement a basic test using the MultithreadedTC library, you have to extend the MultithreadedTestCase class. This class extends the junit.framework.AssertJUnit class that includes all the methods to check the results of the test. It doesn't extend the junit.framework.TestCase class, so you can't integrate MultithreadedTC tests with other JUnit tests.

Then, you can implement the following methods:

  • initialize(): The implementation of this method is optional. It's executed when you start the test, so you can use it to initialize objects that are using the test.
  • finish(): The implementation of this method is optional. It's executed when the test has finished. You can use it to close or release resources used during the test or to check the results of the test.
  • Methods that implement the test: These methods have the main logic of the test you implement. They have to start with the thread keyword, followed by a string, for example, thread1().

To control the order of execution of threads, you used the waitForTick() method. This method receives an integer value as a parameter and puts the thread that is executing the method to sleep until all the threads that are running in the test are blocked. When they are blocked, the MultithreadedTC library resumes the threads that are blocked by a call to the waitForTick() method.

The integer you pass as a parameter of the waitForTick() method is used to control the order of execution. The metronome of the MultithreadedTC library has an internal counter. When all the threads are blocked, the library increments this counter to the next number specified in the waitForTick() calls that are blocked.

Internally, when the MultithreadedTC library has to execute a test, first it executes the initialize() method. Then it creates a thread per method that starts with the thread keyword (in your example, the methods thread1(), thread2(), and thread3()). When all the threads have finished their execution, it executes the finish() method. To execute the test, you used the runOnce() method of the TestFramework class.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.47.224