minitwit icon indicating copy to clipboard operation
minitwit copied to clipboard

Concurrency?

Open qding-bot opened this issue 7 years ago • 3 comments

Hi, If multiple users register with same name at the same time, shouldn't this "select and insert" approach fail?

qding-bot avatar Sep 17 '18 23:09 qding-bot

Hi. I'm not sure what you mean, this part of the code checks that case:

User existingUser = service.getUserbyUsername(user.getUsername());
if(existingUser == null) {
    service.registerUser(user);
    res.redirect("/login?r=1");
    halt();
} else {
    error = "The username is already taken";
}

Are you saying this is not working?

Well, It's possible due to concurrency, isolation level of the db, etc.

eh3rrera avatar Sep 18 '18 15:09 eh3rrera

Yeah. I mean, what if:

Thread1: user1 -> getUserbyUsername('jimmy') -> none found -> registerUser('jimmy') Thread2: user2 -> getUserByUsername('jimmy') -> none found -> registerUser('jimmy')

Then two jimmy users are created.

qding-bot avatar Sep 18 '18 20:09 qding-bot

Right, it's not likely, but it can happen.

Assuming the application is using a single database (or a cluster that can be seen as a single database), the easiest way to solve this could be at the database level, adding a unique constraint to the username column, so the second insertion fails.

eh3rrera avatar Sep 18 '18 22:09 eh3rrera