Got .Net POCO Threadsafe?

This question may seem a little strange, but is related to possible visibility problems. The question is based on an example in the Java programming language (> jdk5), consider:

public class InmutableValue { private int value; public InmutableValue(int value) {this.value = value;} public int getValue() {return value;} } 

Despite the opposite belief, the class above is not thread safe. In a multi-threaded environment, a “value” is not guaranteed to be visible to other threads. In order to make this thread safe, we need to enforce the “happened earlier” rule. This can be achieved by marking the "final" field.

In this case, I wondered if the same is true for the .NET runtime. So take for example:

 public class InmutableValue { private int value; public InmutableValue(int value) {this.value = value;} public int Value { get{return value;}} } 

As far as I know, marking the value field as "readonly" does not give the same guarantees as "final" for java (but I could be terribly wrong, I hope). So, do I need to mark the fields as "mutable" (or use memory barriers, etc.) to ensure visibility for other threads? Or do other visibility rules apply?

+4
source share
2 answers

You are probably worried about processor cores with a weak memory model such as Alpha and Titanium. It has a memory write buffer that can change the order of writing to memory, which makes it possible for a reference to an object to be written down to the value of the value value. Perhaps inspired by the Raymond Chen blog?

However, you are missing important information. To create a stream arrangement, there must be two streams that use an object reference. One that creates the object and saves the link, another that uses this link. This is fundamentally unsafe; synchronization of access to the link to the shared object is required. A synchronization code (such as a lock statement) also flushes the writeback buffer. This prevents a thread that reads a property from ever seeing an obsolete value.

+2
source

In any case, the readonly keyword ensures that the field will be assigned in the constructor, and not elsewhere (inside the class).

And since the constructor is thread safe in the general sense , the created object will return the same value:

 static ImmutableValue imv = new ImmutableValue(123); // thread 1, object is not created imv.Value; // NullReferenceException, as usually // thread 2, object is created imv.Value; //123 // thread 3, object is created imv.Value; //123 

To edit the private field, you need to use Reflection, and yes, you will need to lock the object during the execution of this code to ensure that all threads that are trying to read the value at this moment are frozen.

+1
source

Source: https://habr.com/ru/post/1347433/


All Articles