Take the 2-minute tour ×

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.

share|improve this question
Of course, if all the threads are readers, it might be you don't need any locks ;p –  Marc Gravell Jun 29 '11 at 9:17
And don't lock on the array itself. Locking on objects anybody else knows is usually a bad idea. –  CodesInChaos Jun 29 '11 at 9:23
@CodeInChaos you could argue that locking an object that nobody else knows is kinda pointless... –  Marc Gravell Jun 29 '11 at 9:32
@Marc - I think a thread-safe class might lock on a private readonly object field - the same instance might have methods invoked from different threads and use that object that no-one else can see? –  Kieren Johnstone Aug 9 '11 at 15:44
@Kieren - I meant directly or indirectly :) –  Marc Gravell Aug 9 '11 at 16:41
add comment

2 Answers

up vote 5 down vote accepted

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.


  • 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.

share|improve this answer
Thanks Marc, you are right! I have already edited the post. –  User Jun 29 '11 at 9:16
add comment

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
share|improve this answer
Assuming you use lock(...), the last step is implicit –  Marc Gravell Jun 29 '11 at 9:29
add comment

Your Answer


