开发者

Modifying common resource

开发者 https://www.devze.com 2023-01-18 05:29 出处:网络
My scenario is : I\'ve an excel sheet. Some threads need to modify it at the same time. I need to implement this and I\'m looking for a best practice solution.

My scenario is : I've an excel sheet. Some threads need to modify it at the same time.

I need to implement this and I'm looking for a best practice solution. synchronizedmethod could be a solution? If yes, then wouldn't it create 开发者_StackOverflow中文版starvation problem or every thread may have to wait for long time?

Is any other way round?


An Excel sheet shouldn't be used as working memory. With a resource like that, you have to manage access to it. You can't just let threads try to write to it willy-nilly. I doubt you will find a java Excel module which supports concurrency.

Create a data structure which contains all the data. At the beginning of the process, load the Excel sheet into this data structure. Have the threads modify this data structure instead of the excel spreadsheet. Periodically, or when changes are complete, export the data structure contents back to the Excel spreadsheet.

You will have to handle data concurrency issues yourself. There is no native transaction handling here. You want to make sure you don't write a copy of the spreadsheet that one thread has made some changes to, but not its complete set. This could create confusing results. Also, if two threads are modifying the same data at the same time, that would be confusing too.

Ideally, in a situation like this, the data is held in a database somewhere. This is an ideal place to store data that is concurrently modified by multiple threads. Mainly, it also supports transactions. If you go with this solution, you could create a script which just polls the database every five minutes and updates the Excel spreadsheet.

0

精彩评论

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

关注公众号