Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - concurrency/blocking queue unit testing strategies

I have a program that operates pulls work items off a blocking queue and works on them concurrently. I realise this is a VERY loose description, but can anyone suggest a unit testing strategy/ideas on what to test?

like image 381
Dominic Bou-Samra Avatar asked Jan 10 '12 23:01

Dominic Bou-Samra


People also ask

What is blocking queue in java concurrency?

BlockingQueue is a java Queue that support operations that wait for the queue to become non-empty when retrieving and removing an element, and wait for space to become available in the queue when adding an element.

How is BlockingQueue implemented in java?

Put() Implementation in Blocking Queue This implementation is very similar to enQueue() method. Once the capacity is reached, the thread is blocked or else it's a simple enQueue operation using LinkedList. Once the element is queued, we notify in case other waiting threads are blocked due to an empty queue.

Is java BlockingQueue thread-safe?

BlockingQueue implementations are thread-safe. All queuing methods achieve their effects atomically using internal locks or other forms of concurrency control.

What are the consumer methods available for a BlockingQueue?

Each consumer will take an element from a BlockingQueue using take() method so it will block until there is an element in a queue. After taking an Integer from a queue it checks if the message is a poison pill, if yes then execution of a thread is finished.


2 Answers

Use the worker queue mechanisms in java.util.concurrent and rely on them to test their code. Then just test your worker to make sure it does the correct thing. If it is independent of other threads that should be enough. Otherwise you will likely need to come up with an integration testing strategy on hardware/os/jvm configurations that match your production environment.

like image 110
Bill Avatar answered Sep 29 '22 16:09

Bill


You need to design it to be tested.

So specific suggestions:

  • Make sure that you can place test classes or mocks into the queue
  • Code some early mocks to take longer and be sure that they aren't the first ones completed (demonstrates concurrency)
  • Make sure your results collection is equal in size to all your tests.
  • Make sure your results aren't complete until the time allocated for the longest test.

hmm, it all stems from being able to inject mocks/test classes into the queue.

like image 43
Bill K Avatar answered Sep 29 '22 15:09

Bill K