From bc4f07fbd3dd517560ea2b74bca216a9cb84c343 Mon Sep 17 00:00:00 2001 From: Antonio Aversa Date: Wed, 22 Feb 2023 16:42:50 +0100 Subject: [PATCH] Update rspec 2 --- analyzers/rspec/cs/S2445_c#.html | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/analyzers/rspec/cs/S2445_c#.html b/analyzers/rspec/cs/S2445_c#.html index fc6dc281284..aa8f8ab4612 100644 --- a/analyzers/rspec/cs/S2445_c#.html +++ b/analyzers/rspec/cs/S2445_c#.html @@ -1,12 +1,15 @@ -

Locking on a class field synchronizes not on the field itself, but on the object assigned to it. So locking on a non-readonly field -makes it possible for the field’s value to change while a thread is in a block locked on the old value. That would allow a second thread, locked on -the new value, to enter the block at the same time.

-

Locking on a readonly field of a class which is not private allows external code to lock the field, potentially -interfering with synchronization of methods in that class.

-

Locking on a local variable or on a new instance undermines the synchronization: two different threads running the same method in parallel would -lock on two different object instances. That would allow a second thread, locked on that new value, to enter the same block concurrently.

-

Locking on a string literal is even more dangerous: depending on whether the string is interned or not, different threads may or may not -synchronize on the same object instance.

+

Locking on a class field synchronizes not on the field itself, but on the object assigned to it. Thus, there are some good practices to follow to +avoid bugs related to thread synchronization.

+
    +
  1. Locking on a non-readonly field makes it possible for the field’s value to change while a thread is in the code block locked on + the old value. This allows another thread to lock on the new value and access the same block concurrently.
  2. +
  3. Locking on a readonly non-private field allows, for example, a method from another class to lock on the same field, + potentially interfering with the synchronization.
  4. +
  5. Locking on a local variable or a new instance of an object undermines the synchronization because two different threads running the same method + in parallel will lock on two different instances of the same object, allowing them to access the synchronized block at the same time.
  6. +
  7. Locking on a string literal is also dangerous since, depending on whether the string is interned or not, different threads may or may not + synchronize on the same object instance.
  8. +

Noncompliant Code Example

 private Color colorObject = new Color("red");
@@ -48,6 +51,9 @@ 

Compliant Solution

See