简体   繁体   中英

One thread writes data while not being read, many threads read while data is not being written

I have more than just a basic understanding of locks and synchronized blocks. However, as far as i know, they just ensure that a single thread has access to some data at a time.

What i need is a little bit different. Lets say i have a String. One and only one thread my change it (assign some value to it), and lets assume this operation takes a lot of time - 3 seconds.

A lot of other threads need to read the value of this String, and do some operations (execute a block of code) with the assumption that the value remains unchanged until the whole block executes. Lets assume that this block takes 5 secs to execute.

So, the "writer" thread must not update the String while there are threads using/reading it, and the "reader" threads must wait for an update (by the "writer") to finish before starting to use it.

I could solve this with a lock if there was only 1 "writer" and 1 "reader", but how can i do this now that there is 1 "writer" and N "readers". Note that many "readers" may access the data at the same time.

By the way, it is kind of hard to provide code, since it is hundreds of line, includes internet access, database access...

I know i can avoid this problem by changing my implementation but i have reasons to prefer this implementation - and it's not i'm too lazy to change it.

What you are looking for is a ReadWriteLock . Where multiple threads can read at the same time. A write is blocked until the reading threads finish. And reads are blocked until the writing thread finishes.

If operations take that long, you are doing something wrong. The right method is to calculate the new data, however long it takes, without affecting the old data, and then replacing the old with the new data in one go. And destroying the old data only when everyone using it is finished with it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM