0

knowing that Java is different from PHP, is there a way to reconstruct such a behaviour in Java?:

In PHP I can make something like this:

function a_function() {
    static $var = "something";
    // do something...
}

After I call this function the first time, all subsequent calls to this function would result in a $var not being reset to "something" at all (its value will be preserved across multiple calls to this function, i.e. if the value of $var will be changed while // do something... is executed, then after a subsequent call, the value of $var would be the last assigned value to $var).

I was wondering if there's a same/like method to do this in Java (declaring a static local variable in a method in Java is not possible, so I guess I can achieve this in some other ways). I thought of making a protected or private static field and use it across multiple calls to a method (here a possible way with a boolean):

public class A {
     protected static boolean isSomething = "false";

     public void aMethod() {
         // do something... e.g. change the isSomething boolean 
         // if some condition occurs
     }

}

What do you think about this approach and what would you do in such a case? Are there other ways to accomplish this?

Thanks for the attention!

tonix
  • 6,671
  • 13
  • 75
  • 136

1 Answers1

2

Yes, you can do it the way you show in your second example.

Keep in mind that you will have problems with that pattern in multi-thread situations.

It is also not very elegant as a design choice. And depending on your situation its dangerous and error-prone.

Use with care (that is: don't do this unless you know you need it)

Usually you would want something like that to be thread-save and atomic. You can do it with the volatile keyword if you also take care of synchronization.

public class A {
    private static volatile boolean status = true;
    public flipStatus() {
        synchronized(this) {
            status = !status;
        }
    }
}

Even better is the use of the Atomic classes from java.util.concurrent.atomic

import java.util.concurrent.atomic.*;
public class A {
   private static final AtomicBoolean status = new AtomicBoolean(true);
   public boolean flipStatusToTrue() { // return true if value has been flipped
       return status.compareAndSet(false, true);
   }
   public boolean flipStatusToFalse() { // return true if value has been flipped
       return status.compareAndSet(true, false);
   }
}
Angelo Fuchs
  • 9,825
  • 1
  • 35
  • 72