I have rather general question, please advice.
I have a servlet.
This servlet has private field.
Private field is a kind of metadata stuff (public class Metadata{//bla-bla-bla}).
When GET request is processed, this metadata is used to perform some operation.
I want to implement POST method in the same servlet. User uploads file and Metadata field is updated.
The problem: concurrent access to this private field with Metadata object shared among sereval web-threads using one servlet instance. POST method operaton (Update Metadata object) can lead to Metadata inconsistent state and concurrent GET request can be failed.
The question: what is the best way to update Metadata object while GET requests are running?
Dummy solution:
-
During each GET request,, at the very beginning
-
Synchonize Metadata object and clone it in one block, then release it.
-
Concurrent GET requests work with clone verstion of Metadata object which is consistent.
-
During each POST request.
-
Synchonize Metadata object and update its fields.
-
Release Metadata object.
Please advice or critisize.
Using synchronized methods set and get in the Metadata class is fine but may slower your web app in case you have multiple readers and (much) less writers:
(Excerpt from that nice post)
So using a multiple read single write strategy may be better in term of performance in some cases as explained also in the same Java5 ReadWriteLock interface doc:
A ready to use implementation is the ReentrantReadWriteLock.
Take a look at the previous post for a nice tutorial on how to use it.