java - Wait for specific condition to become true in threads -


i have application makes http requests site, ant retrives responses, inspects them , if contain specific keywords, writes both http request , response xml file. application uses spider map out urls of site , sends request(each url in sitemap fed separate thread sends request). way wont able know when requests have been sent. @ end of request want convert xml file other format. in order find out when request have ended use following strategy :

i store time of each request in varible (when new request sent @ time later time in variable, varible updated). start thread monitor time, , if difference in current time , time in varible more 1 min, know sending of requests has ceased. use following code purpose :

class monitorreq implements runnable{     thread t;     monitorreq(){         t=new thread(this);         t.start();     }     public void run(){         while((new date().gettime()-last_request.gettime()<60000)){              try{                   thread.sleep(30000);//sleep 30 secs before checking again              }              catch(ioexception e){                  e.printstacktrace();               }         }         system.out.println("last request happened 1 min ago @ : "+last_request.tostring());         //call method conversion of file     } } 

is approach correct? or there better way in can implement same thing.

your current approach not reliable. race conditions - if thread updating time & other thread reading @ same time. difficult processing of requests in multiple threads. assuming task finishes in 60 seconds..

the following better approaches.

if know number of requests going make before hand can use countdownlatch

main() {    int noofrequests = ..;    final countdownlatch donesignal = new  countdownlatch(noofrequests);     // spawn threads or use executor service perform downloads    for(int = 0;i<noofrequests;i++) {       new thread(new runnable() {          public void run() {             // perform download             donesignal.countdown();          }       }).start();    }     donesignal.await();  // block till threads done. } 

if don't know number of requests before hand can use executorservice perform downloads / processing using thread pool

main() {

  executorservice executor = executors.newcachedthreadpool();   while(morerequests) {     executor.execute(new runnable() {       public void run() {         // perform processing       }     });   }    // finished submitting requests processing. wait completion   executor.shutdown();   executor.awaittermination(long.max_value, timeunit.seconds); 

}


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -