tryLock method non blocking method?

The documentation of the tryLock method says that it is a non-blocking method
which allows you to obtain/acquire the lock (if that's possible at the time of calling the method).

But I wonder: how can you obtain a lock and still guarantee at the same time that
your method (tryLock) is non-blocking?! Acquiring the lock implies that you're
trying to access a guarded section of code so it should block (if you're not lucky
i.e. you should block at least in certain scenarios). Could anyone explain the logic
behind this? Purely from a logical standpoint: I don't quite understand how this can
be done at all (guaranteeing that the method doesn't block). Unless they use another
thread of course within the code of the tryLock itself...

http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/Lock.html#tryLock%28%29

Jon Skeet
people
quotationmark

Acquiring the lock implies that you're trying to access a guarded section of code so it should block (if you're not lucky i.e. you should block at least in certain scenarios)

If that's the behaviour you want, you should just use the lock method. The whole point of tryLock is that you use it when you don't want to block if the lock isn't available.

In terms of how that's implemented, it's up to individual implementations - so you should look at whichever implementation you're interested in. I would personally think it reasonable for those to use synchronized internally, if they knew that no user-specified code was ever run inside the synchronized blocks - in other words, it could block briefly for internal house-keeping, but not for the duration of the lock itself.

Or of course an implementation which had access to appropriate machine-level instructions could use compare-and-swap etc... heck, AtomicBoolean.compareAndSet could probably be used for a very simple version of this.

people

See more on this question at Stackoverflow