Java – Algorithm to create custom ConcurrentHashMap

concurrencyjava

I tried to look into concurrent HashMap source code to look in to how it is implemented. To me it looked very difficult to understand((In no way i am saying its not required :))). I thought if i need to implement it myself and how should i go about it. Here is brief algo about it :-

1) Maintain a list of 16(Default) custom lock objects extending Reentrant lock.

2) Lock will have the state(of type AtomicInteger) say lockState which will be 0 if not in use. If somebody has acquired the lock, it will be 1

3) Before any update/create operation (For example :- in PUT operation), CMH will see if any lock in the list is available with lockState.compareAndSet(int 0, int 1) If result of compareAndSet is true then acquire the lock

4) Once done set lockState to 0 again.

This is just skelton and in know there will be much scope of optimization. But just wanted to confirm if i am on write track or you guys see some serious flaw in it? .

Best Answer

ConcurrentHashMap does not use any Lock instances at all. It uses directly the Unsafe class which calls directly processor instructions (such as compareAndSet or volatile read). This means it's way more faster than with Lock.

What you can do is to use ReadWriteLock instead of ReentrantLock to have a better performance when reading.

Related Topic