If you mean that you want to unconditionally block any other thread from accessing some object, then you simply can't do it. That is, if you have some object:
public Object foo = new Object();
There is nothing you can do in your thread to prevent other threads from accessing foo
. A lock won't work, as you pointed out, because a lock is a cooperative mutual exclusion device. Nothing except convention prevents somebody from writing code that ignores the lock and accesses the object.
You could conceivably wrap the object in a class that enforces mutual exclusion, but then all you're doing is adding a lock or something similar. Even then, you'd have to create a special method that implements the semantics you're looking for (i.e. peek-and-add). And even that isn't foolproof because somebody could use reflection to access the underlying data structure directly.
Your peek-and-add operation is a bit unusual. I don't know enough about your application to say for sure, but in most cases there's a more conventional way to implement the functionality you want. This is particularly true with something like ConcurrentBag
, where Peek
will give different results depending on which thread is accessing it.