The database has a “clients” table.
A client application in Java have a method with the following algorithm:
List<Client> candidateClients = clientRepository.findAllClientsWithFilter(...);
Client client = ... //selecting a client from the list using a complex and confusing algorithm
client.setUser(userId);
And then several threads follow this algorithm and a race occurs between them. Two threads for two users receive the same client and try to take it over.
If two threads work in the same process, then everything is decided by the synchronized section. But how to synchronize them if they are running not only in different instances of the service, but even on different physical machines?
Is it possible to somehow configure locking in the database without locking the entire table?