Hello. I have such a problem: In the application, many threads run randomly through MultiValueMap, which uses some Collection as value. These streams take a collection from Map, extract an element from it, remove it from the collection and process it. If the collection is empty, then the flow should submit a task for updating the collection for this key to the spec. pool. This pool contains a single thread that updates collections by key. The problem is that such a situation is possible when several threads take on the same collection one key, it turns out to be empty, and essentially the same task is sent to the update. I want to avoid this. In a nutshell, I would like it to look like this:
Collection coll = myMap.getCollection(key); if(coll.isLocked()) { // ΠΠΎΠ»Π»Π΅ΠΊΡΠΈΡ Π·Π°Π»ΠΎΡΠ΅Π½Π°, ΡΠ»Π΅Π΄ΠΎΠ²Π°ΡΠ΅Π»ΡΠ½ΠΎ Π΅Ρ Π½Π΅ ΡΡΠΎΠ³Π°Π΅ΠΌ Π° ΠΏΠ΅ΡΠ΅Ρ
ΠΎΠ΄ΠΈΠΌ ΠΊ ΠΊΠΎΠ»Π»Π΅ΠΊΡΠΈΠΈ Π΄Π»Ρ Π΄ΡΡΠ³ΠΎΠ³ΠΎ ΠΊΠ»ΡΡΠ° } if(coll.isEmty()) { coll.lock()// Π±Π»ΠΎΠΊΠΈΡΡΠ΅ΠΌ ΠΊΠΎΠ»Π»Π΅ΠΊΡΠΈΡ ΡΡΠΎΠ±Ρ Π½ΠΈΠΊΠ°ΠΊΠΎΠΉ Π΄ΡΡΠ³ΠΎΠΉ ΠΏΠΎΡΠΎΠΊ Π½Π΅ ΠΌΠΎΠ³ ΠΊ Π½Π΅ΠΉ //ΠΎΠ±ΡΠ°ΡΠΈΡΡΡΡ, ΡΠ»Π΅Π΄ΠΎΠ²Π°ΡΠ΅Π»ΡΠ½ΠΎ Π½Π΅ ΠΌΠΎΠ³ ΠΏΠΎΠ»ΡΡΠΈΡΡ Π΄Π»Ρ Π½Π΅ΠΉ isEmpty() ΠΈ Π·Π°ΡΠ°Π±ΠΌΠΈΡΠΈΡΡ //ΡΠ°ΡΠΊ Π½Π° Π²ΡΠΏΠΎΠ»Π½Π΅Π½ΠΈΠ΅ pool.submit(new MyTask(coll)); } This will be the case in handler threads. And in the update thread something like that:
... //ΠΠ±Π½ΠΎΡΠ²ΠΈΠ»ΠΈ ΠΊΠΎΠ»Π»Π΅ΠΊΡΠΈΡ coll.unLock(); // Π‘Π½ΡΠ»ΠΈ Π±Π»ΠΎΠΊΠΈΡΠΎΠ²ΠΊΡ,ΡΠ΅ΠΏΠ΅ΡΡ ΠΏΠΎΡΠΎΠΊΠΈ ΠΎΠ±ΡΠ°Π±ΠΎΡΡΠΈΠΊΠΈ ΡΠ½ΠΎΠ²Π° ΠΌΠΎΠ³ΡΡ ΠΎΠ±ΡΠ°ΡΠ°ΡΡΡΡ ΠΊ ΠΊΠΎΠ»Π»Π΅ΠΊΡΠΈΠΈ Question: how to implement such functionality correctly? (inherit from some collection and make the volatile lock flag. somehow very simple) + Considering the specifics of the problem, please advise the collection for the map? Considering that the elements from the collection need to be deleted, somehow I donβt want to use ArrayList for such purposes, due to possible brakes with System.arrayCopy (...)