最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

postgresql - concurrency in spring jpa with postgres - Stack Overflow

matteradmin4PV0评论

I am using jpa in my spring boot application (postgres) and have some entity called car. In the beginning cars are created without assignedUser field in database.

Then trough certain process (post request) users can assign cars to themselves, where they will get the first car that has assignedUser field null and more recent creationTimestamp and status not DELETED. The method finds the first car in these conditions and assigns it to the user that made the request. At this point field assignedUser is populated.

In order to prevent concurrent updates and make sure that if many users try to request cars at the same time (they should all get different cars) I have implemented a optimistic locking mechanism

@Entity
public class Car{

    @Id
    private Long id;
    private String status;
    private String name;
    private double price;
    private String assignedUser;
    private Instant creationTimestamp;

    @Version
    private int version; // Version field for optimistic locking

    // Getters and setters
}

The ideia here is if I get an OptimisticLockException it means the record was updated in between by another process and I will try the assign operation again.

My problem is that at any point in time users can execute a clear operation, where all cars that have assignedUser null are updated to status DELETED. I might have thousands of cars in this scenario so I will update in batches (I cannot use optimistic locking here)

How can I prevent following scenarios when clear operation and assign requests happen at the same time?

  1. clear operation from modifing a car that was just assigned to a user
  2. assign operation from assigning a car that was just cleared (status = DELETED) ?
Post a comment

comment list (0)

  1. No comments so far