sri
sri

Reputation: 9

How to maintain order of tasks for asynchrounous operations using multithreading

I am writing a java application where the central datastructure will be updated both with the request and corresponding response from external systems. How can I make sure there are no race conditions? Below is how I implemented.

I receive request from GUI and I process it and store in hashmap of hashmap and then forward the request to external system for which I get the response asynchronously. When I receive the response based on some id that I sent earlier, I update the datastructure (hashmap of hashmap)

I created one thread that handles request from GUI and another for handling responses from external system. I have created 2 linkedblockingqueues - one for requests and another for responses

I am using executor service to create multiple threads for request & response. How do I make sure things are executed in order ? This is an order management system and I dont want an amend to be sent before new order is sent.

Upvotes: 0

Views: 52

Answers (1)

jordiburgos
jordiburgos

Reputation: 6302

Use Hastable, it is the synchronized implementation of a Map.

The synchronized implementation will prevent that more than one thread accesses it at the same time.

https://docs.oracle.com/javase/8/docs/api/java/util/Hashtable.html

Upvotes: 1

Related Questions