2015-02-12 14 views
1

有人問我這個面試:僞碼是好的在Java中使用鎖定(面試)的最佳實踐是什麼?

//Assume you have a list or A Queue 
//1 - How do you make Sure pushing to list is safe? 
//1 - My Ans: 
     void push(Element e){ 
      Synchronized(this){ 
       list.push(e); 
       } 
      } 
//2- Interviewer said Ok, there is better way to do this without Synchronized word 
      void push(Element e){ 
       writeLock.Lock(); 
       list.push(e); 
       writeLock.UnLock(); 
      } 
//3- He said Ok, but wouldn't work if there are 16 threads, How can I make sure only one thread can write? His answer was more like a "Semaphore" 
     void push(Element e){ 
      readLock.lock(16), //meaning get read lock on all 16 thrds 
       writeLock.Lock(); //then allow to write 
       list.push(e); 
       writeLock.UnLock(); 
       readLock.Unlock() 
      } 

我不知道我的理解他的解決方案在#3,任何人都關心解釋和闡述?

+2

如果他在談論['ReadWriteLock'(https://docs.oracle。 com/javase/7/docs/api/java/util/concurrent/locks/ReadWriteLock.html),他錯了。 「只要沒有寫入器,讀取鎖就可以同時被多個讀取器線程持有,寫入鎖是排他性的。」 – EJP 2015-02-12 03:41:38

+0

目前還不清楚'readLock.lock(16)'是什麼意思。這個問題不能一概而論。答案取決於特定類的語義是100%。你將不得不用更具體的例子編輯你的問題,否則沒有答案。 – Radiodef 2015-02-12 05:09:15

+0

我認爲這是一個僞代碼。問題是關於概念 – 2015-02-12 05:14:42

回答

2

想法是讀者只有在沒有寫入正在進行時才能讀取。換句話說,閱讀是免費的同步。所以16個線程可以同時讀取。 但是,當你想寫你鎖定一切(讀取和寫入過程),只做寫作。面試官可能會從自爲的是concurrencyLevel默認值的ConcurrentHashMap採取的想法是16

我建議你看看http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentHashMap.html