开发者

Lock & Validate or Validate & Lock?

Suppose you pass an array as argument to a given method, say,

开发者_运维知识库public static DoSomething (string[] array)
{
    // Do something with array here.
}

and that inside the method you use some instructions that throw an exception if array contains invalid data. In a multi-threaded environment where multiple threads may be accessing array, in what order should you procede?

1) Lock the array to make sure only one thread operates on it at the same time and, after locking, validate it, releasing the lock as soon as you finish working; or

2) Check the array immediately for validity and, in case it is valid, lock it and do your work.


You can't lock "the array" if it is null; but it wouldn't matter anyway - the reference can't change; it is still the same reference even if the contents change. So you can defer the lock until you are interested in the contents.

So:

  • null check
  • lock
  • check contents / use contents

If you mean general validity - it depends on whether any threads are going to change the contents. If not... meh, no locks needed. If they are changing the contents, you need to lock before you validate, otherwise your validations are moot.


I believe that the code within the method doesn't need to lock the item passed as argument. Instead, the caller should do it!!

It's a matter of chain of responsibility: the object that accesses shared data (ie. a static field in a class) should null-check and lock, and the method supposed to operate on its input should not consider any mulithreading issues, assuming that the argument is exclusively used by it.

This is only my opinion, so

  • Null check
  • Lock
  • Call method
  • Unlock on return
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜