While i was looking at some legacy application code i noticed it is using a string object to do thread synchronization. I'm trying to resolve some thread contention issues in this program and was wondering if this could lead so some strange situations. Any thoughts ?
private static string mutex= "ABC"; internal static void Foo(Rpc rpc) { lock (mutex) { //do something } }
Also, since your string is not const or readonly , you can change it. So (in theory) it is possible to lock on your mutex . Change mutex to another reference, and then enter a critical section because the lock uses another object/reference.
When a thread invokes a synchronized method, it automatically acquires the intrinsic lock for that method's object and releases it when the method returns. The lock release occurs even if the return was caused by an uncaught exception.
There is no such thing.
Strings like that (from the code) could be "interned". This means all instances of "ABC" point to the same object. Even across AppDomains you can point to the same object (thx Steven for the tip).
If you have a lot of string-mutexes, from different locations, but with the same text, they could all lock on the same object.
The intern pool conserves string storage. If you assign a literal string constant to several variables, each variable is set to reference the same constant in the intern pool instead of referencing several different instances of String that have identical values.
It's better to use:
private static readonly object mutex = new object();
Also, since your string is not const
or readonly
, you can change it. So (in theory) it is possible to lock on your mutex
. Change mutex
to another reference, and then enter a critical section because the lock uses another object/reference. Example:
private static string mutex = "1"; private static string mutex2 = "1"; // for 'lock' mutex2 and mutex are the same private static void CriticalButFlawedMethod() { lock(mutex) { mutex += "."; // Hey, now mutex points to another reference/object // You are free to re-enter ... } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With