What is the closest to ConcurrentHashMap and NavigableMap in Java?

Jacek Furmankiewicz jacek99 at gmail.com
Fri Nov 15 07:21:58 PST 2013


On Friday, 15 November 2013 at 07:42:22 UTC, ilya-stromberg wrote:
> On Thursday, 14 November 2013 at 22:12:10 UTC, Jacek 
> Furmankiewicz wrote:
>> On Thursday, 14 November 2013 at 21:36:46 UTC, ilya-stromberg 
>> wrote:
>>> On Thursday, 14 November 2013 at 21:31:52 UTC, Jacek 
>>> Furmankiewicz wrote:
>>> How often do you change the data? Probably, you should use 
>>> `immutable` variables.
>>
>> Customer specific. It may change once a year. It may change 
>> multiple times per second for a while, then nothing again for 
>> weeks.
>>
>> Others may do mass loads of business rules, hence do mass 
>> changes every few hours.
>>
>> Next to impossible to predict.
>
> You can use `immutable` variables. It allows you to share the 
> data without any synchronization. Like this:
>
> class MyData
> {
>    int data1;
>    string data2;
>
>    //creates new object
>    this(int data1, string data2)
>    {
>       this.data1 = data1;
>       this.data2 = data2;
>    }
>
>    //modify the data
>    immutable(MyData) editData(int i) const
>    {
>       //copy this object - we can't change immutable variables
>       MyData dataCopy = new MyData(this.data1, this.data2)
>
>       //modify the data copy
>       dataCopy.data1 += i;
>
>       //assume that `dataCopy` is immutable
>       return cast(immutable(MyData)) dataCopy;
>    }
> }
>
> shared myMap;
>
> //map implementation
> synchronized class MyMap
> {
>    HashMap!(int, immutable(MyData)) map;
>
>    void foo()
>    {
>       map[1] = new immutable MyData(1, "data");
>    }
>
>    void bar()
>    {
>       map[1] = map[1].editData(5);
>    }
> }
>
> //init map
> shared static this()
> {
>    myMap = new MyMap();
> }
>
> void main()
> {
>    myMap.foo();
>    myMap.bar();
> }


So what happens when the "write" operation is doing

  map[1] = map[1].editData(5);

and at the same time 50 threads are simultaneously reading the 
value in map[1]?.

Is that reassignment operation thread safe?
Or would I get corrupted reads with potentially a partially 
overriden value?

Jacek


More information about the Digitalmars-d-learn mailing list