开发者

Multi-threaded Application with Readonly Properties

Should my multithreaded application w开发者_如何学Pythonith 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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜