Created a Java application on spring boot. Declared a variable int x=0;

Opened it through the browser, and wrote x=1; to the variable x x=1;

I opened the same application in the second tab of the browser, and already in it through the web interface, for example through an html element, assigned x=2 .

If the third client in the third tab writes in x=3 , then the previous two clients will also have x equal to three, and for example, when you click on a button to view the result, the code will run

 if (x = 0) System.out.println("x = 0") elseif (x = 1) System.out.println("x = 1") else if (x = 2) System.out.println("x = 2") else if (x = 3) System.out.println("x = 3") 

and all three will display the same thing, namely: x = 3;

Those. one application is able to run on only one thread. How to solve this problem?

  • Nothing of the kind, each http request is processed in a separate stream. And the symptoms you describe are related to the fact that all the bins are singletones, including controllers. - Sergey Gornostaev
  • @SergeyGornostaev I do not quite understand how the application runs. It is launched on the server via java -jar, and is located in the RAM of the server machine along with all its variables. When I access the application via http, I change the variable x to x = 2, for example. The http request was completed, but my application is still in memory with x = 2. The question is, how does the application running on java work, and how to make every user access it as from scratch? - Timur Baimagambetov
  • It's simple, just store the data only in local variables of the method. - Sergey Gornostaev
  • I probably understood. When we go from the browser, we create a controller object. It executes the request, then the http request is completed, and the object is deleted by the garbage collector. When re-accessing even to the same page of the same user, a new controller object will be created, and so, with each http-request, an object will be created that will work and then be destroyed by the garbage collector. I correctly described? - Timur Baimagambetov
  • one
    The controller object is created once - when the server starts. Each new request in a separate thread runs the controller's methods. If the variable x declared inside the method, then the memory for it is allocated in the stack frame and the variable exists for exactly as long as the method runs. If a variable is declared as a class field, memory for it is allocated on the heap and it will not be removed until the server is stopped. - Sergey Gornostaev

0