I thought that you have to synchronize all methods that involve fields that can be accessed by several threads at the same time.
the writeObject is synchronized but the readObject is not this could cause problems as you could read the wrong value...
where do I go wrong in my thinking?
Why is he readObject() not synchronized?
Under discussion
Comments (4)
- Popular
- New
- Old
You must be signed in to leave a comment
Nouser
29 December 2020, 17:59
Reading doesn't change state. So simulatous reading is OK.
In write mode you can open a file just once.
0
Liliane Top Backend Developer at Procura
29 December 2020, 18:16
But is uses shared resources ..
So while I just update the file you're reading the old file which hasn't been flushed yet to the main memory.
0
Liliane Top Backend Developer at Procura
29 December 2020, 18:18
the value and count are shared resources....
0
Nouser
29 December 2020, 18:40useful
Yes, you're right. When leaving the synchronized block of the write block something like a flush is happening internally and the fields are getting updated (that's similar to volatile, when the code reaches a volatile variable, all fields get synchronized with the main memory). And afaik when you open a file in write mode, only that object can access the file. All other have to wait. After reading the update of the fields. When then other threads again can access the file, the content has been updated and they get valid data again.
At least that's how I explained it to me. And I haven't found much more info about that in the net. Maybe others were more successful thatn me ;)
+1