Is using an existing object rather than creating a specific lock object safe?

后端 未结 2 1049
轻奢々
轻奢々 2021-01-14 16:26

EDIT: As it turns out when I was browsing I found a question the appears to be the same as mine which I didn\'t find earlier: Difference between lock(locker) and lock(variab

相关标签:
2条回答
  • 2021-01-14 16:51

    You've pretty much answered your own question. For locking, it's generally better to create an object specifically for the purpose, and usually held privately for use by accessor methods that express synchronisation logic at a high level.

    0 讨论(0)
  • 2021-01-14 16:53

    The general rule is that you want to control the scope of the object your locking on to prevent some unknown code from causing unexpected behavior. In this case you are using a private instance variable so you are probably OK as long as you are not handing out references to it.

    If you are handing out references and locking on it and other code is locking those references (e.g. when modifying the collection) changing the behavior could easily introduce threading bugs.

    If someone puts it into a public property that counts as "handing out references" if they lock on it your call to lock will block until they unlock it. Whether this is desirable or not depends on what they are doing with the collection.

    Having the object locked will have have no effect on using the object for any purpose other than synchronization.

    0 讨论(0)
提交回复
热议问题