3

I have used basic object.wait() , object.notify() , object.notifyAll() in multi-threaded programming.

I know we have the package java.util.concurrent and it has java.util.concurrent.locks package. Specifically in java.util.concurrent.locks we have : Condition, Lock and LockSupport (among others).

I read online about this package, and understood basics of Lock and Condition. However, I didn't understand LockSupport. I did search to understand LockSupport , however didn't find anything relevant which can help me understand what it is used for. I have seen that in LockSupport we have methods like park() , unPark() etc. However, I didn't get what is the purpose of LockSupport, it seems to be doing more or less same like Lock?

Can anyone please help me understand why we have LockSupport and what it does that Lock don't do.

CuriousMind
  • 8,301
  • 22
  • 65
  • 134

1 Answers1

2

It's a helper class with very low level concurrency mechanisms that are used by the other classes. Unless you want to write your own higher level concurrency structures, you probably won't use it.

There are other helper classes like java.util.concurrent.locks.AbstractQueuedSynchronizer, which provide other mechanisms (e.g. wait queues in case of AQS) to the classes that you are more likely to use, like ReentrantLock and so on.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
  • Thanks for your answer. So does it mean that we should use LockSupport only if we are creating a new DataStructure which need synchronization / thread safe? I read javadoc of this, it has multiple concepts within like : `permit`, `Semaphore` etc. Can you elaborate a bit more for understanding, please? – CuriousMind Feb 22 '20 at 17:43
  • 2
    @CuriousMind not data structure, but your own concurrency mechanism if you were to come up with a specific kind of lock or something. Otherwise there's no reason to need the kind of low level access that `LockSupport` provides. – Kayaman Feb 22 '20 at 17:47
  • Thanks for your reply. So it means that if we want to implement `our own way of synchronization` (not necessarily using Locks, Synchronized keyword etc.) then we can create a new implementation (a Class) which internally would use LockSupport. And `LockSupport` internally uses `sun.misc.Unsafe` to do so. Is this correct conclusion? – CuriousMind Feb 22 '20 at 18:09
  • 1
    @CuriousMind if you want to create a `CuriousMindLock` class or a `CuriousMindConcurrentQueue`, then you might find use from `LockSupport`, otherwise you'll probably never use that class. – Kayaman Feb 22 '20 at 18:16