线程安全使用同步

时间:2014-08-19 09:53:14

标签: java mysql multithreading concurrency ibeacon

我正在尝试在JAX-RS项目中编写一些代码。由于这是与iBeacon相关的,我需要生成为给定用户存储的主要次要号码。

注册用户的代码如下:

/**
 * Register a user to the application. Registration requires unique
 * username and unique email address. 
 * @Override
 * @param username the username to register with
 * @param password the password to register with
 * @param email the email to register with
 * @param firstname the users firstname
 * @param lastname the users lastname
 * @return RegistrationStatus to determine if the method succeeded or not
 * @throws MajorMinorException 
 */
public synchronized RegistrationStatus register(String username, String password,String email, String firstname, String lastname) throws MajorMinorException {

    if(StringUtilities.stringEmptyOrNull(username, password, email, firstname, lastname)){
        throw new IllegalArgumentException ("Unable to register the user as a value which is needed is null or empty");
    }

    if(!StringUtilities.validEmail(email)){
        throw new IllegalArgumentException("The email is not in a valid format to register with");
    }

    if(!StringUtilities.validPassword(password)){
        throw new IllegalArgumentException("The password " + password + " for user " + username + " was not in a valid format");
    }

    RegistrationStatus result = RegistrationStatus.FAILED;
    try {
        int major = super.getMajorMinor(true, username, source.getConnection());
        int minor = super.getMajorMinor(false, username, source.getConnection());
        if(major == -1 || minor == -1){
            throw new MajorMinorException("Major/Minor value was -1, possible bad data: " + username + " " + email);
        }
        Tuple<Integer, Integer> majorMinorPairs = IBeacon.incrementMajor(major, minor);
        result = register(username, password, email, firstname, lastname, majorMinorPairs.getFirst(), majorMinorPairs.getSecond(), source.getConnection());
        logger.info("major minor generated for user " + username + "  major: " + majorMinorPairs.getFirst() + " minor: " + majorMinorPairs.getSecond());
    } catch (SQLException e) {
        logger.error("An error occured when registering", e);
        return result;
    }
    return result;
}

现在我可以预见一个可能存在问题的潜在情况。原因是super.getMajorMinor(true, username, source.getConnection());在数据库表上执行MAX,然后将其递增1。因此,我假设有两个最大语句可能同时发生(在用户注册该对之前),因此我们会得到一个脏的读/写。

我可以锁定表以保持数据的完整性,但另一种解决方案是同步寄存器方法。这与锁定我相信的表有相同的效果,但性能影响会更糟吗?

由于

0 个答案:

没有答案