Reputation: 126
I am calling 4 threads separately at the same time. These threads are making http calls and are fetching data from separate links. Now, I created a class, instantiated a single object of that class for accessing the data. All four threads are accessing the data simultaneously. Now the problem is, the data is not stored in a synchronized manner . One threads data is being replaced by another data. How to prevent this? How to do it in synchronized manner? Any ideas? Please help.
Upvotes: 0
Views: 186
Reputation: 35242
A good pattenr for this is immutable objects. The advantage - they need no synchronization, so needs no complex synchronization logic
An object is considered immutable if its state cannot change after it is constructed. Maximum reliance on immutable objects is widely accepted as a sound strategy for creating simple, reliable code.
Immutable objects are particularly useful in concurrent applications. Since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state.
Immutable means that the internal state of the object cannot change after construction, ergo, an object can only be in an defined state and never be in a "between" state, as object creation is atomic. This also means that if you like to change any attribute of your object you have to create a new one. For example a String
or BigDecimal
is immutable and Date
should have been.
Programmers are often reluctant to employ immutable objects, because they worry about the cost of creating a new object as opposed to updating an object in place. The impact of object creation is often overestimated, and can be offset by some of the efficiencies associated with immutable objects. These include decreased overhead due to garbage collection, and the elimination of code needed to protect mutable objects from corruption.
For further info check out this section in the java documentation: http://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html
And here is a guide what to take into account with syncronizing with immutable objects: http://docs.oracle.com/javase/tutorial/essential/concurrency/imstrat.html
Upvotes: 2
Reputation: 2048
You can uso the clause:
synchronized (objectToLock){
.....
actions
.....
}
Hope it helps you!
Upvotes: 2