How would I go about doing this in a client-server application?
I want to basically let clients access the same data through separate threads, and I want avoid concurrency thread issues so I’m asking for examples.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
To access the same piece of data, you just need to ensure you’re accessing the same instance of the class. So 2 threads hitting the same singleton, or the same object obtained from some factory will both be getting the same piece of data. Obviously the exact scenario depends on your application.
Concurrency issues will generally only arise when some piece of data is being modified. Say for example you had the following class:
Then that would not necessarily be thread safe. To make it thread safe, you need to lock on an object monitor. This could be done in one of two ways in this scenario:
This solution would lock calls to getData and setData on the Container instance’s lock. This is fine, except if you were to add a third method to this class, which didn’t use data at all, then it would also be blocked if any thread was inside getData or setData. To make it more specific, you could do:
This then uses the data variables object lock. The advantage of this is if you add a third method which doesn’t use data, then it won’t be blocked by calls to getData or setData.
That’s a basic overview of Java’s concurrency safety, hope it helps.
Note that the client-server nature of your problem doesn’t really change much. If your threads are being created by, for example, thread per request via java servlets or something then this all applies in exactly the same way.