Reputation: 67
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.
Upvotes: 0
Views: 2290
Reputation: 2201
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:
class Container {
private List<?> data;
public List<?> getData() {
return this.data;
}
public void addData(Object data) {
this.data.add(data);
}
}
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:
class Container {
private List<?> data;
public synchronized List<?> getData() {
return this.data;
}
public synchronized void addData(Object data) {
this.data.add(data);
}
}
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:
class Container {
private List<?> data;
public List<?> getData() {
synchronized (this.data) {
return this.data;
}
}
public void addData(Object data) {
synchronized (this.data) {
this.data.add(data);
}
}
}
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.
Upvotes: 2