I want to keep the main thread alive. I found 3 options, and i wonder which one is the best. what are the differences, and why??
is there any wasting resource among them?
while(true){}
thread.join()
CountDownLatch(1).await()
I tried them, and those worked well.
while(true){}
thread.join()
CountDownLatch(1).await()
Here:
while(true){}
does a "hot" wait. It means: your CPU spins at 100%, doing nothing. Maybe, maybe, if you are really lucky, the JVM detects that and is able to not burn CPU cycles like that.
Whereas, for join(), we find:
When we invoke the join() method on a thread, the calling thread goes into a waiting state. It remains in a waiting state until the referenced thread terminates.
( from this tutorial )
So, join() sounds like the more healthy approach. await()
should work in similar ways.
The downside of these two methods: they react to thread interrupts, so it might probably a good idea to put them into a "while true" loop.