简体   繁体   中英

What is best Practice to use Locks in Java (Interview)?

I was asked this in interview: Pseudo code is Ok

//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()
             }

I am not sure I understood his solution at #3, Anyone cares to explain and elaborate?

Idea is readers can read only if there is no write is going on. In other words, reading is synchronization free. So 16 thread can concurrently read. However, When you want to write you lock everything (both read and write processes) and only do the writing. Interviewer might have taken the idea from the ConcurrentHashMap since default value for concurrencyLevel of that is 16.

I suggest you look at http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentHashMap.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM