Reputation: 1219
here is my Timer
scheduler
timer.schedule(new SuperOne(),new Date(),10);
In SuperOne
class in run
method i am calling synchronized
method By using above code That task is only working once.
My requirement is that It has to call the synchronized
method for every minute(60 seconds).
Here timer scheduler is not working what I expect ... Is it because I am running synchronized
method ?
Please help me In this
*EDIT: Its working for first time (calling one time ) and not calling after 10 milliseconds *
This is the code has to run
private boolean proxyEnabled=false;
public synchronized void statusChecker()
{
StopWatch sWatch = new StopWatch();
ResourceBundle resource = ResourceBundle.getBundle("resources.application");
System.out.println(resource.getString("url"));
try {
URL url = new URL("https://www.google.com/");
HttpURLConnection urlConnection;
if(proxyEnabled) {
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxYhost", portNumber));
sWatch.start();
urlConnection =(HttpURLConnection) url.openConnection(proxy);
System.out.println(urlConnection);
} else {
urlConnection =(HttpURLConnection)url.openConnection();
sWatch.start();
}
System.out.println(urlConnection.getResponseCode());
in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
if(in!=null)
{
System.out.println("The resopose TIme is -- >"+ sWatch.toString());
}else
{
System.exit(0);
}
}catch(Exception e)
{
e.printStackTrace();
System.exit(0);
}finally
{
sWatch.stop();
}
}
Class which extends TimerTask
public class SuperOne extends TimerTask{
boolean flag = false;
@Override
public synchronized void run() {
// TODO Auto-generated method stub
try {
System.out.println("*** * ** Thread started ** ** *** ");
Thread th = Thread.currentThread();
System.out.println(th.isAlive());
CheckServer cs = new CheckServer();
cs.statusChecker();
}
catch(Exception e)
{
System.out.println("Exception in Run IterFace "+e);
e.printStackTrace();
}
}
}
Upvotes: 0
Views: 247
Reputation: 9115
You've made run
synchronized
, which means that only one thread can every access that function at a time (which means realistically only one task can ever be active at a time). I do not believe this is what you intended to do. I imagine what you intended to do was make what run
calls during its execution synchronized
, so that only one of the running tasks can call it at a time to ensure consistency.
A lot of people get tripped up on exactly what synchronized
does, because it doesn't do what a lot of people expect it to (although it does do what its name implies if you think about common use cases for it). See the Java synchronized tutorial for more.
Upvotes: 1