views:

36

answers:

2

Should my multithreaded application with read only properties require locking? Since nothing is being written I assume there is no need for locks, but I would like to make sure. Would the answer to this question be language agnostic?

Without Lock:

Private Const m_strFoo as String = "Foo"
Public ReadOnly Property Foo() As String
    Get
        return m_strFoo.copy()
    End Get
End Property

With Lock:

Private Const m_strBar as String = "Bar"
Public ReadOnly Property Bar() As String
    Get
        SyncLock (me)
            return m_strBar.copy()
        End Synclock
    End Get
End Property

Edit: Added Const to Fields

+1  A: 

You could forego the lock if the string member is never going to change. However, if you're going to modify it from time to time, the public member method would need to synchronize it's access to the private member.

Jim Lamb
You can also forego locks on reading a value, even when it is changed regularly by other code, if your primary concern is speed and not up-to-millisecond correctness. E.g. WHen it doesn't really make a difference whether the answer is 2,000,000 or 2,000,005 or even 2,000,500. Same goes for smaller numbers in for example logs. Do you really care whether something has been asked for 1309 times or 1308 times? If not, you could forego the lock.
Marjan Venema
+1  A: 

Properly designed immutable objects are generally thread safe. The risk is that "properly designed" is a complicated subject - see Peter Veentjer's treatment for an example of the pitfalls of immutable thread safety in Java.

Matt
A synchronize within the constructor should solve Peter Veentjer example of myInt. Interesting article!
Shiftbit