locked
Is a private collection in a class, thread safe? RRS feed

  • Question

  • User836564631 posted

    Hi,

    Is a private collection in an instance of a class, threadsafe?

    In order to illustrate my question, please have a look at the following "stupid" code.

    As you will see "myClass" instantiates a "private" collection.

    "anotherClass" instantiates "myClass" and populates the collection, then passes the instance of "myClass" to a shared method of another class "aThirdClass", which in turn "gets" and "sets" the contents of the collection.

    So, the question, is this code ThreadSafe or do I systematically have to use the SyncLock, each time I need to get access to the contents of the hashTable?

    Public Class myClass
    	Private _myCollection As HashTable = New HashTable(StringComparer.OrdinalIgnoreCase)
    
    	Public Sub AddValue(ByVal key As String, ByVal value As String)
    		If (Not _myCollection.ContainsKey(key)) Then
    			_myCollection.Add(key, value)
    		End If
    	End Sub
    
    	Public Function GetValue(ByVal key As String) As String
    		Dim strValue As String = String.Empty
    		If (_myCollection.ContainsKey(key)) Then
    			strValue = _myCollection(key)
    		End If
    		Return strValue
    	End Function
    End Class
    
    Public Class anotherClass
    	Public Shared Sub myRoutine()
    		Dim anInstance As myClass = New myClass()
    
                    
    		anInstance.AddValue("key1", "value1")
    		anInstance.AddValue("key2", "value2")
    
    		aThirdClass.DoSomething(anInstance)
    
    		If (Not String.IsNullOrEmpty(anInstance.getValue("key3")) Then
    		End If
    	End Sub
    End Class
    
    Public Class aThirdClass
    	Public Shared Sub DoSomething(ByVal theInstance As myClass)
    		Dim strValue As String = theInstance.GetValue("key2")
    		theInstance.AddValue("key3", "value3")
    	End Sub
    End Class
    
    

    Many thanks for your feedback

    Saturday, February 9, 2013 10:12 AM

Answers