Locking on Strings

前端 未结 2 1108
挽巷
挽巷 2021-01-17 02:00

2 Questions:

  1. str field is shared between two instance of A type [line 2]
  2. What\'s implications according to following code ?



        
2条回答
  •  离开以前
    2021-01-17 02:29

    Locking on strings in this manner can be dangerous. According to Section 3.10.5 of the Java Language Specification:

    Literal strings within different classes in different packages likewise represent references to the same String object.

    What this means is that if another class contains the same string literal, it will refer to the same String object and could result in a deadlock.

    It would be better to use one of the explicit locks from the java.util.concurrent.locks package or even a new Object().

    Example:

    private final ReentrantLock lock = new ReentrantLock();
    String str = "hello";    
    
    public void run(){
        lock.lock(); 
        try{
            System.out.println(str+" "+Thread.currentThread().getName());
            Thread.sleep(100);
            System.out.println(str+" "+Thread.currentThread().getName());
        }
        finally{
            lock.unlock();
        }
    
    }
    

提交回复
热议问题