I am trying to send request to server in every 2 seconds in a thread and check if there is something for me give it back to me….For getting value i have to use callable. I am not able to figure out how to run callable thread in every 2 seconds and get value back from it…here is my sample code of callable implementation…
public String call(){
boolean done = true;
String returnData = "";
while(done){
try {
returnData = post.getAvailableChat();
if(!returnData.equals("")){
System.out.println("Value return by server is "+returnData);
return returnData;
}
return null;
} catch (IOException ex) {
done = false;
Logger.getLogger(GetChatThread.class.getName()).log(Level.SEVERE, null, ex);
}
Now here is my main class code i know i did it wrong here in main class because my code will not go to next line after while loop….but please tell me how to do it
Callable<String> callable = new CallableImpl(2);
ExecutorService executor = new ScheduledThreadPoolExecutor(1);
System.err.println("before future executor");
Future<String> future;
try {
while(chatLoop_veriable){
future = executor.submit(callable);
String serverReply = future.get();
if( serverReply != null){
System.out.println("value returned by the server is "+serverReply);
Thread.sleep(2*1000);
}//End of if
}//End of loop
} catch (Exception e) {
You rightly picked a ScheduledThreadPoolExecutor but you don’t take advantage of the methods it provides, in particular in your case: scheduleAtFixedRate instead of submit. You can then remove the sleep part as the executor will handle the scheduling for you.