Good day !

Before asking a question I will describe my task (this can help with the answer).

There is an ΠΈΠ·ΠΎΠ±Ρ€Π°ΠΆΠ΅Π½ΠΈΠ΅ . This image I break into a ΠΌΠ°Ρ‚Ρ€ΠΈΡ†Ρƒ images. And each element of the matrix is ​​generated by code. In the following, I have to write each element to the database . Everything worked without streams and this pattern, just the recording speed was unsatisfactory. (used Ρ‚Ρ€Π°Π½Π·Π°ΠΊΡ†ΠΈΠΈ , синглСтон - ΠΊΠΎΠ½Π½Π΅ΠΊΡ‚ΠΎΡ€ , etc.)

I did everything according to this example.

In this example, he has the number of products made equal to the number of products taken. I.e:

Then he put these products 10 times

 for (int i = 0; i < 10; i++) { cubbyhole.put(i); } 

And then he took them 10 times

 for (int i = 0; i < 10; i++) { value = cubbyhole.get(); } 

In my case, the number of fabricated elements is n-Π½Π½ΠΎΠ΅ . Are there any ways to track the number of fabricated items? I try to make it so that each generated element is immediately recorded in the database .

    1 answer 1

    Usually when using the producer-consumer pattern, the number of items produced is unknown. Therefore, the use of so-called. poison pill is a marker object, which means the completion of the generation of elements. Often null used as such, but depends on the task. It is important that this is some value that is either not found in the produced elements, or it logically means the completion of the generation of elements (for example, the "END-OF-FILE" line at the end of the file). Moreover, if the elements in the queue put N producers, then while consuming the elements, you need to track the number of poison pills received - the processing will be completed after N pieces have been received.

    A couple of examples:

    There is another option: a queue of items should support shutdown. An example of this is the BlockingCollection<T>.CompleteAdding() method and the BlockingCollection<T>.IsCompleted . Unfortunately, I don’t know if there is a similar API in Java.

    PS I also advise you to consider using BlockingQueue as a queue of items. This is a more "modern" approach that allows you to abandon the use of locks.

    • Thanks for the answer ! By the way, I found the example of BlockingQueue first, than the one I’m doing now. I thought that I would not deal with it. Apparently it will be necessary to understand. And with poison pill you can show an example? Link to tutorial or something like that. - kxko
    • @kxxko added a couple of links to the answer. - andreycha
    • Thank you so much for the answer! There is an opportunity to ask one question in the chat? It is too small to create a theme for it. Also about threads. - kxko
    • @kxxko where to go? - andreycha
    • Over here - kxko