工作中涉及到了一個普通的http服務(wù),接收http請求,業(yè)務(wù)中需要保證同一個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(() -> {
//使用隨機數(shù)模擬user并發(fā)
test(random.nextInt(3));
});
}
}
private static void test(int a) {
//隨機字符串+數(shù)字
String s = "asdfasdf";
String lock = s + a;
synchronized (lock) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(lock);
}
}
}
打印出來的結(jié)果
asdfasdf0
asdfasdf0
asdfasdf2
asdfasdf1
asdfasdf1
asdfasdf0
asdfasdf0
asdfasdf2
asdfasdf2
asdfasdf0
明顯是沒鎖到.
在網(wǎng)上查了查原因,發(fā)現(xiàn)synchronized比較鎖是使用的==,比較的是內(nèi)存地址,因為每次都會new一個String,所以內(nèi)存肯定不同.
解決思路:
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™ 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();
}
解決