Every source i saw in the www states that a Condition Object
is get by using the newCondition method
on a Lock object
ReentrantLock.newCondition()
But by navigating the java sources i saw that a implementation is already available.
ConditionObject // implements Condition
I dont want to be the only one but thats why I am asking.
Can I Use this Condition Object to wait/notify/notifyAll with synchronized methods?
Or is it any better to stick to the combination with locks?
Additionally:
There is so much code in the await() method
of a Condition object
. Could there by a performance difference between the traditional wait/notify/notifyAll?
CodePudding user response:
I'm not sure where did you find that ConditionObject
, but it's most likely some internal object used by a lock class.
Condition cannot exist by itself without a lock (a monitor, to be precise), that's because await/signal need access to that monitor.
When you call await
method it'll put current thread on the wait list of the monitor, suspends it (parks it, so it's excluded from scheduling) and it'll release the lock, so that other threads can acquire it.
When you call signal
, then one thread in the wait list of the monitor is being resumed.
CodePudding user response:
You can't use it without its associated lock. ConditionObject
is connected to AbstractQueuedSynchronizer
which can be used to create locks, semaphores and other things so you don't need to worry about the details.
You've been given easy to use concurrency primitives in java.util.concurrent.locks
package. I recommend you use them, you have less chance of getting things wrong that way.
CodePudding user response:
Let's give a conceptual answer here:
But by navigating the java sources i saw that a implementation is already available.
In other words: should your code that uses a public standard API rely on an internal implementation detail of that API?
The answer to that is (almost) always: of course not!
You make your code dependant on the contracts that the public API provides, not at all on how it is implemented. Thing is, (at least theoretically) such internal implementation details can change with any new version of Java. Sure, if it is a structural thing then the compiler might tell you, but what if not?
Meaning: when you study java standard library code, then to improve your overall knowledge on programming (one can learn a lot from reading and thinking about this code). But unless you have very good reasons to do so: never ever let the internals guide your code!