Last post Sep 10, 2011 01:28 AM by PNasser
Sep 09, 2011 10:36 PM|boeledi|LINK
I am developping a web site and I have questions linked to the notion of "thread safety".
Could someone answer the following questions?
1. Classes that only expose static methods
Are classes that only expose static methods "thread-safe"? In other words, can I always trust the arguments (even ArrayList) the were passed to these methods?
For example, when invoking a static method of these classes with an ArrayList, do I need to lock the ArrayList before passing it in arguments?
In addition, do I need to lock the ArrayList in the static method, to make sure it is synchronized?
2. Classes without any static variable and ArrayList
For classes that do not contain any static variable, is it necessary to lock an ArrayList?
Public Class myClass
Public Function returnSomething() as ArrayList
Dim arrList as ArrayList = new ArrayList()
Public Class callerClass()
Private _oneClass as New myClass()
Public Sub doSomething()
Dim oneList as ArrayList = oneClass.returnSomething()
For each obj as Object in oneList
'do something with obj
In this kind of code, where class instances are independant to each other, do I still need to use SyncLock <arrayName>.SyncRoot in order to make sure I can trust the content of the ArrayList or could I use the code as shown here
3. Lock vs SyncLock
Which of these 2 locking means is the "best"?
The notion of Thread-Safety is not well explained, mainly the reasons why in Web developments we actually need to consider locking things...
Any good explanation will be welcome...
Thanks in advance
Sep 10, 2011 01:28 AM|PNasser|LINK
1. It depends on the static method. If you take in an ArrayList as a reference, then you cannot assume that it's thread-safe. The reason is that ArrayList is not a thread-safe data structure. If you are passing in a variable by value, then it won't matter,
as the static method will be using a copy of whatever the variables was. If something else changes ArrayList outside the method, it will be changing the original, not the copy.
2. This would be thread-safe. oneClass.returnSomething() will return a new ArrayList, and then you loop through that array. There is nothing here that can reach that ArrayList that might modify it outside of sync of your code
3. From my understanding these two are the same. Not 100% though