I have a thread running, calling out to an external web service to retrieve some data. The thread should however exit the run method when a certain condition is met in a database (count number of rows of certain type and see if they equal a value). I am thinking of implementing this and have thought of the following ways.
-
Processing thread:
run() { while(not [db call to get row count] = expected number ) { call web service // wait for some time for the next call? not sure // if this is the way to do it Thread.sleep(200); } } -
Have an external thread monitoring the database status and updating an AtomicBoolean variable.The processing thread woud check this variable in the while loop every time.
ProcessingThread:
private Runnable dbStatusThread; run() { while(dbStatusThread.booleanValue == false) { call web service // wait for some time for the next call Thread.sleep(200); } }
I tried implementing the second option, but even though the boolean is set to true, it isn’t always reflected and the run() doesn’t always immediately exit. I’m reading JCIP as I write this, but does anyone know of a standard way of doing this kind of thing? Thanks.
I did not put an
==in the condition but a>=instead since maybe you’ll get more lines than you want.Even if some other process or thread is filling the database at the same time this code is valid. If there is no other process filling the database, you could just have a for-loop calling the web service a set number of times, without checking the database at each step.
Note that a database is kind of “synchronized” to start with: when you check the number of lines in the database, you get the current picture.