I have a situation, where two threads are trying to check for a userId, and when it doesn't appear, they try to create it. The problem is, the userId is SQL created and by the time the 2nd thread tries to save it has already passed the "if user == null" error checking.
relevant portion of User.java:
@Column(name = "username", unique=true, length = 150)
private String username;
DemoApp.java :
String usrName = "testuser";
// ur is a CrudRepository from Spring Boot for Users
User existingU = ur.findOneByUsername(usrName); // Both Threads cannot find usrName
if(existingU == null){
//#thread 1 is able to save the user, but thread 2 causes "unique constraint SQL error."
existingU = new User(usrName, "firstname", "lastname");
ur.save(existingU); // Thread 1 succeeds here... Thread 2 fail
lg.info("Saved new user"); // Thread 1 outputs this.
// Thread 2 errors out on .save and crashes
} else {
lg.info("User found in database"); // this never happens
}
UserRepository (for ur variable)
import org.springframework.data.repository.CrudRepository;
public interface UserRepository extends CrudRepository<User, Long> {
User findOneByUsername(String userName);
}
QUESTION: How can I make sure that the CrudRepository findByUsername is super-up-to-date and won't go into existingU==null if-statement?? Is there some more elegant way to design this situation? Perhaps there is no solution because the threads seem to launch at the same millisecond.