同步相同的字符串值 [英] Synchronize On Same String Value

查看:34
本文介绍了同步相同的字符串值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个为 Web 应用程序创建新用户的方法.该方法本身调用一个静态帮助器类,该类创建一个 SQL 语句,该语句执行对我的数据库的实际插入.

Let's say I have a method that creates a new user for a web application. The method itself calls a static helper class that creates a SQL statement that performs the actual insertion into my DB.

public void createUserInDb(String userName){
    SQLHelper.insertUser(userName);
}

我想同步这个方法,这样它就不能被不同的线程同时调用如果传入的参数(userName)在这些线程上是相同的.我知道我可以使用 synchronized 关键字来同步方法执行,但这通常会阻止不同的线程同时执行该方法.如果传入的变量相同,我只想阻止并发执行.Java 中是否有一个简单的构造可以让我这样做?

I want to synchronize this method such that it cannot be called concurrently by different threads if the passed in parameter (userName) is the same on those threads. I know I can synchronize method execution using the synchronized keyword, but this would prevent different threads from concurrently executing the method in general. I only want to prevent concurrent execution if the passed in variable is the same. Is there an easy construct in Java that would let me do this?

推荐答案

不能保证具有相同值的两个字符串在 Java 中会指向同一个实例,尤其是如果它们是根据用户输入创建的.

There is no guarantee that two strings with the same value would point to the same instance in Java, especially if they are created from user input.

但是,您可以使用 intern() 方法,这将保证它使用的是同一个实例:

However, you can easily force them into the string pool using the intern() method, which would guarantee it's the same instance being used:

public void createUserInDb(String userName){
    String interned = userName.intern();
    synchronized (interned) {
        SQLHelper.insertUser(interned);
    }
}

这篇关于同步相同的字符串值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆