-1

In my code i have to use multiple timers/delays.

So i want to create a method to reset timers. But the timer never resets to null and i cant figure out why not. if someone can point me out why my timer in the second example is never being reset to null it would be greatly appreciated!

How it works:

          public class BIhcsTemplate extends BComponent implements Runnable {
                
                Clock.Ticket delayTimer; //simple clock from a library
                
                public void onExecute() throws Exception {
            
               // if true reset timer
                if (getBExample()){
                  if(delayTimer!=null){              
                  delayTimer.cancel();                        
                  delayTimer=null;}
            }
    
               if (delayTimer==null){
              //start the timer
      }
 }

What i would like to do, but doesnt work:

    public class BIhcsTemplate extends BComponent implements Runnable {
        
                Clock.Ticket delayTimer; //simple clock from a library
        
                public void onExecute() throws Exception {
        
                if (getBExample()){ 
               resetTimer(delayTimer)       
               }
               if (delayTimer=null){
               //start timer}
               }
            }

       public void resetTimer(Clock.Ticket timerToReset){        
       if(timerToReset!=null){               
       timerToReset.cancel();              
       timerToReset=null; // <== assigned value null is never used according to intellij        
      }}
        
mittens13
  • 17
  • 7

1 Answers1

0

Basically what happens is that you send a pointer to the object to the method but that's a new object reference. Then you set that copy to Null but the original object is not changed, just that reference you have there changes to null. So you can do:

 public Clock.Ticket resetTimer(Clock.Ticket timerToReset){        
    if(timerToReset!=null){               
       timerToReset.cancel();              
       timerToReset=null;  
    }
    return timerToReset;
 }

And then use it as:

  delayTimer=resetTimer(delayTimer) 

More on the matter: Is Java "pass-by-reference" or "pass-by-value"?

Veselin Davidov
  • 7,031
  • 1
  • 15
  • 23