Spring boot several threads work incorrect

Alexey :

I'am making my first client-server application. This is an immitation of elevator. I've done server with using spring boot and client part on JavaFX. My elevator must move between floors within 10 seconds.

This is my POST method where i send target floor: (I dont'n know why but integer values don't arrive)

@PostMapping()
    public String postEndPoint(@RequestBody String floor) {
        return elevatorService.setFloor(Integer.valueOf(floor));
    }

Set method:

public String setFloor(Integer floor) {
        if (!isPressed(floor)) { // if button isn't pressed, add to list
            list.add(floor);
        }
        targetFloor = list.get(list.size() - 1);
        motion();
        if (list.get(list.size() - 1) == currentFloor) { // when we arrive, delete pressed button
            list.remove(list.size() - 1);
        }
        return String.valueOf(floor);
    }

 private boolean isPressed(Integer floor) {
        return list.contains(floor);
    }

and the motion logic:

private void motion() {
        new Thread(() -> {
            try {
                    Thread.sleep(10000);
                    if (currentFloor < targetFloor) {
                        currentFloor++;
                    } else {
                        currentFloor--;
                    }
                    if (currentFloor != targetFloor) {
                        motion();
                }
            } catch (InterruptedException ignored) { }
        }).start();
    }

It works good if i click on the desired floor and wait when elevator arrive, but if I call the elevator on several floors at the same time it works incorrect. Can somebody help me to solve this problem? Thank you.

hfontanez :

I am sure your problem is that you are not using atomic values. Change your primitive integers for an Atomic Integer object.

I suggest you read this to learn more about why and how to use atomic values: https://docs.oracle.com/javase/tutorial/essential/concurrency/atomicvars.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=156830&siteId=1