Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can run() return objects?

Assuming that this is the scenario:

class A extends TimerTask{
  int a;
  public void run(){
    //operation to be performed periodically
  }
}

and

class B{
  int delay=2000,interval=3000;
  A objectA;
  public static void main(String[] args){
    Timer t=new Timer();
    t.scheduleAtFixedRate(new A(),delay,interval);
  }
}

Can't run() return objects? If I make such a change, incompatibility is cited. Why?

like image 599
P R Avatar asked Feb 21 '26 04:02

P R


2 Answers

As you can see in the method-declaration, the returntype of run is void. Therefore the method can't directly return an object. But what you can do, is storing an object at the instance-level of class A and declaring a method on A from which you can get the stored object, when it's operation is finished

like image 199
Turbokiwi Avatar answered Feb 23 '26 17:02

Turbokiwi


Use a FutureTask (and Future) with ExecutorService (see examples on API pages).


Example:

public static void main(String[] args) throws Exception {

     FutureTask<String> future = 
             new FutureTask<String>(new Callable<String>() {
         public String call() {
             try {
                 Thread.sleep(1000);
             } catch (InterruptedException e) {
                 e.printStackTrace();
             }
             return "Hello World!";
         }
     });

     ExecutorService executor = Executors.newFixedThreadPool(10);
     executor.execute(future);

     System.out.println(future.get());
}
like image 44
dacwe Avatar answered Feb 23 '26 17:02

dacwe