Static Variables and Methods

I came across a class that was configured as follows:

public class MyClass {

  private static boolean started = false;

  private MyClass(){
  }

  public static void doSomething(){
    if(started){
      return;
    }
    started = true;
    //code below that is only supposed to run
    //run if not started
  }
}

My understanding of static methods is that you should not use class variables in them unless they are constant and change. You should use options instead. My question is: why is this not broken when called multiple times by executing MyClass.doSomething (). It seems to me that this should not work, but it does. It will only pass after the if statement is executed.

So can someone explain to me why this won't break?

+3
source share
9 answers

doSomething() started , doSomething(). doSomething() , started , started true ... , -. , , started , - .

+11

, . , , .

:

  • . , - false.
  • doSomething . if . start true .
  • doSomething . .

, , , doSomething() , , , if , .. .

+6

. - -

public class MyClass {

  private static AtomicBoolean started = new AtomicBoolean(false);

  private MyClass(){
  }

  public static void doSomething(){
    boolean oldValue = started.getAndSet(true);
    if (oldValue)
      return;
    }

    //code below that is only supposed to run
    //run if not started
  }
}

, AtomicBoolean getAndSet .

, , ( , webapp , , ).

+6

- , , .

, , .

, , . Java, , , . , , - .

.

, started - , , ?

+2

.

, doSomething true, if, .

+1

, . , .

-:

private int foo = 0;

.

started is false - initial state.
MyClass.doSomething() - statered is now true
MyClass.doSomething() - started is STILL true

MyClass foo = new MyClass();
foo.started -> it STILL true, because it static
foo.doSomething() - not sure you can do this in Java, but if you can, it be STILL TRUE!

, , , .

+1

: " , ". !

. , , . , ( , , , ).

+1

( ). , ?

0

, , ,

I assume that only static members are available. It is not necessary to be permanent!

My question is why this does not break when called multiple times by doing MyClass.doSomething (). It seems to me that this should not work, but it does. It will only pass after the if statement

In accordance with the existing logic. Only the first call does //code to be runpart

0
source

Source: https://habr.com/ru/post/1704119/


All Articles