开发者

general Java design of consuming an async web service

i need to consume a batch web service where I send a unique id to identify myself, then the service sends back a unique response id that I am to use some minutes later to get the info I need. in general, what is a good way to开发者_运维知识库 keep track of the response id and call the service again at some later time to get the real response?


The easy solution is to stick the ID and timestamp a map* or list, then have a loop in a separate thread that wakes up and processes all IDs older than a certain age. (Make sure that the map or list is thread-safe.) However, if your app goes down and gets relaunched, it will lose track of pending requests. If you must handle that case, use a database.

* One specific solution is to use a SortedMap keyed by timestamp. You must make sure every timestamp is unique so you should expect not to put more than one element per millisecond into the map. Then to put an ID into the map, let the timestamp be System.currentTimeMillis(), and while the timestamp is already a key in the map, increment it. Then put the (timestamp, ID) pair into the SortedMap. This solution is convenient because the loop thread can just read elements of the SortedMap from the beginning until they are too new and then stop, because all the oldest elements are at the beginning of the map.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜