Reputation: 917
I have a dictionary which I want to make it static. For suppose I have a dictionary which has some data.If I am accessing this dictionary by two processes at the same time then my data mismatches. How can I solve this problem.
for example In a dictionary I have key A- values 1 2 3 4 5 key B- values 6 7 8 9 10
When I am accessing this dictionary by two processes one reads data for A and other reads data for B. Then I have results sets where B contains A values.
Upvotes: 0
Views: 752
Reputation: 947
You just need to use a ConcurrentDictionary, in System.Collections.Concurrent
private static readonly ConcurrentDictionary<TKey, TValue> dictionary =
new ConcurrentDictionary<TKey, TValue>();
Upvotes: 1
Reputation: 10337
If your program is written in .NET, you can take a look at this related question regarding the best way of implementing a thread-safe Dictionary, with links and C# sample code…
Upvotes: 0
Reputation: 578
If your program is written in Java, you need to synchronize any methods that retrieve and set the values.
For example:
public synchronized int getValue() {
return value;
}
The 'synchronized' keyword ensures that two processes do not read or set data concurrently.
This is achieved by the JVM acquiring a lock on the object, to only allow one thread to access it at a time. The code is then executed, and once completed the lock is released. If another thread is waiting, this thread can then acquire a lock on the object.
Upvotes: 0