How it works...

In this recipe, you have used the LinkedTransferQueue class parameterized with the String class to implement the producer/consumer problem. This LinkedTransferQueue class is used as a buffer to share the data between producers and consumers.

You have implemented a Producer class that adds strings to the buffer using the put() method. You have executed 100 producers and every producer inserts in the buffer 10,000 strings, so you insert 1,000,000 strings in the buffer. The put() method adds the element at the end of the buffer.

You also have implemented a Consumer class, which gets a string from the buffer using the take() method. This method returns and deletes the first element of the buffer. If the buffer is empty, the method blocks the thread that makes the call until there are strings in the buffer to consume. You have executed 100 consumers, and every consumer gets 10,000 strings from the buffer.

In the example, first, you have launched the consumers and then the producers, so, as the buffer is empty, all the consumers will be blocked until the producers begin their execution and stores strings in the list.

The following screenshot shows part of the output of an execution of this example:

To write the number of elements of the buffer, you have used the size() method. You have to take into account that this method can return a value that is not real, if you use them when there are threads adding or deleting data in the list. The method has to traverse the entire list to count the elements and the contents of the list can change for this operation. Only if you use them when there aren't any threads modifying the list, you will have the guarantee that the returned result is correct.

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

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