Niko
Niko

Reputation: 8153

Handling two Maps with multiple threads

I am trying to achieve following:

  1. I have two Maps (not sure yet which safe to use and works properly)
  2. Both are like Map<Integer, Object> (let's say from now Map1 and Map2
  3. Object is always inserted to Map1 first
  4. The Integer value is incremented with AtomicInteger every time Object is inserted to Map1
  5. After insertion I need to get the first inserted Object from the Map1 and move it to Map2 and then perform asynchronous operation with the Object
  6. In the callback of that operation I need to remove the Object from Map2 and repeat

Map1 is sort of a queue and Map2 contains all running operations. The amount of running operations can be adjusted to be more than 1 at a time.

For example I execute 5 operations in a row and max amount for running operations is 4, the sequence would be:

Put all 5 into Map1 with 0,1,2,3,4 ids. Then indexes 0,1,2,3 should be removed and moved to Map2. When first Object from Map2 is ready, it should be removed and the last from Map1 moved to Map2.

I tried with ConcurrentHashMap but iterating it with Iterator.next() started from the last inserted item and had some problems removing item from Map2 when the object got ready.

Upvotes: 0

Views: 48

Answers (1)

Ajay George
Ajay George

Reputation: 11875

Map1 is sort of a queue

Use a Blocking Queue which is a FIFO data structure.

Upvotes: 2

Related Questions