I am facing an issue where I have a data stream that sends unordered data. I'm trying to find a way to receive the data in random order, but send it in order.
As an example, I'll receive object4
and then object3
and then object1
. I'll need my system to store object4
and object3
when they arrive and immediately send object1
. In the future, when object2
arrives, I'll need the system to immediately send object2
and then recheck the array to send object3
and object4
and so on.
Some more info:
- The data is sure to be received fully, so there's no missing data.
- The data is numbered (e.g:
object1
,object20
).
My current solution is:
- When receiving a new object...
- if the new object is in order, send it immediately.
- If the new object is not in order
- Store it in a list
- Check the list if it contains the next object to send
- After sending an object...
- Check the list if it contains the next object to send
So this system is rechecking the list for items to send on two events:
- When a new not-in-order object is added.
- After a successful send
As for sending
After a successful send, the sent object will be removed from the list
As for concurrency
For sake of argument, assume its a producer-consumer relationship where the list is concurrently accessed from both players:
- The producer thread is pushing new data to the list.
- The consumer thread is checking the list, sending and deleting the sent data.
My question is that, is this a good mechanism? Is there a better data structure to help me with this issue?