Java uses strings as locks, and guarantees that the same content is the same lock

Java uses strings as locks, and guarantees that the same string content is the same lock

Use google tool:

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>31.0.1-jre</version>
</dependency>

Example usage:

// 使用com.google.common.collect的Interner类
private final Interner<Object> interner = Interners.newWeakInterner();


public void test() {
    
    
	// 代码加锁示例:
	// 只要字符串内容相同,不管是实例化的字符串对象还是通过“”创建的字符串对象,都是同一把锁
	String authtoken = new xxx; 或者“”
	synchronized (interner.intern(authtoken)) {
    
    

    }
}

Guess you like

Origin blog.csdn.net/u014438244/article/details/131212014