使用synchronize锁对象无法锁string

工作中涉及到了一个普通的http服务,接收http请求,业务中需要保证同一个user只能同时有一个线程在处理,需要手动加锁.
由于只部署单个实例,所以没有使用分布式锁,第一想到的还是一个synchronized,使用synchronized对user加锁.测试代码如下:

/**
 * @author: hman
 * @date 2019-04-25
 * @desc: //TODO
 */
public class TestSynchronized {


  public static void main(String[] args) {
    ExecutorService executorService = Executors.newFixedThreadPool(10);
    Random random = new Random();
    //10个线程
    for (int i = 0; i < 10; i++) {
      executorService.execute(() -> {
        //使用随机数模拟user并发
        test(random.nextInt(3));
      });

    }
  }

  private static void test(int a) {
//随机字符串+数字
    String s = "asdfasdf";
    String lock = s + a;
    synchronized (lock) {
      try {
        Thread.sleep(2000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      System.out.println(lock);
    }
  }
}

打印出来的结果

asdfasdf0
asdfasdf0
asdfasdf2
asdfasdf1
asdfasdf1
asdfasdf0
asdfasdf0
asdfasdf2
asdfasdf2
asdfasdf0

明显是没锁到.

在网上查了查原因,发现synchronized比较锁是使用的==,比较的是内存地址,因为每次都会new一个String,所以内存肯定不同.

解决思路:
1.改成小于-127->127的Integer,因为在这个范围的Integer是直接从常量池中取得.建议直接使用key取hash取模128即可
2.也是最简单最有效的方法.使用String的intern方法.

/**
   * Returns a canonical representation for the string object.
   * <p>
   * A pool of strings, initially empty, is maintained privately by the
   * class {@code String}.
   * <p>
   * When the intern method is invoked, if the pool already contains a
   * string equal to this {@code String} object as determined by
   * the {@link #equals(Object)} method, then the string from the pool is
   * returned. Otherwise, this {@code String} object is added to the
   * pool and a reference to this {@code String} object is returned.
   * <p>
   * It follows that for any two strings {@code s} and {@code t},
   * {@code s.intern() == t.intern()} is {@code true}
   * if and only if {@code s.equals(t)} is {@code true}.
   * <p>
   * All literal strings and string-valued constant expressions are
   * interned. String literals are defined in section 3.10.5 of the
   * <cite>The Java&trade; Language Specification</cite>.
   *
   * @return  a string that has the same contents as this string, but is
   *          guaranteed to be from a pool of unique strings.
   */
  public native String intern();

简单介绍,这个intern方法在newString的时候会先去字符串常量池中判断有没有,如果有就用,没有的话就new然后放进去,这样可以完美解决这个问题

代码修改成:

String lock = s + a;
    synchronized (lock.intern()) {
      try {
        Thread.sleep(2000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }

解决

推荐阅读更多精彩内容