I'm making a Java application with an application-logic-thread and a database-access-thread. Both of them persist for the entire lifetime of the application and both need to be running at the same time (one talks to the server, one talks to the user; when the app is fully started, I need both of them to work).
However, on startup, I need to make sure that initially the app thread waits until the db thread is ready (currently determined by polling a custom method dbthread.isReady()
).
I wouldn't mind if app thread blocks until the db thread was ready.
Thread.join()
doesn't look like a solution - the db thread only exits at app shutdown.
while (!dbthread.isReady()) {}
kind of works, but the empty loop consumes a lot of processor cycles.
Any other ideas? Thanks.
If you want something quick and dirty, you can just add a Thread.sleep() call within your while loop. If the database library is something you can't change, then there is really no other easy solution. Polling the database until is ready with a wait period won't kill the performance.
Hardly something that you could call elegant code, but gets the work done.
In case you can modify the database code, then using a mutex as proposed in other answers is better.
You could do it using an Exchanger object shared between the two threads:
And in the second thread:
As others have said, do not take this light-hearted and just copy-paste code. Do some reading first.
Use a CountDownLatch with a counter of 1.
Now in the app thread do-
In the db thread, after you are done, do -
This idea can apply?. If you use CountdownLatches or Semaphores works perfect but if u are looking for the easiest answer for an interview i think this can apply.
Requirement ::
Answer ::
Job Done!! See example below
Output of this program ::
You can see that takes 6sec before finishing its task which is greater than other thread. So Future.get() waits until the task is done.
If you don't use future.get() it doesn't wait to finish and executes based time consumption.
Good Luck with Java concurrency.
A lot of correct answers but without a simple example.. Here is an easy and simple way of to use
CountDownLatch
: