multithreadingcopyonwritearraylist

Two threads updating in CopyOnWriteArrayList


Two thread Lets suppose t1 and t2 both trying to perform update operation in copyOnWriteArrayList at same time ......then which thread changes will get copied in original list first?


Solution

  • In this scenario, the two threads will attempt ... simultaneously ... to acquire the write lock on the CopyOnWriteArrayList. One thread will get the lock immediately. The other thread will be blocked until the thread that got the lock releases it.

    What if two threads get the lock at the same time.

    It cannot happen.

    Two threads can attempt to get a lock at the same time. However, only one thread will get the lock immediately. The other will be blocked. This is a fundamental invariant of locks. The instruction sequences used to acquire and release locks ... and ultimately the CPU hardware guarantee that the invariant is not violated.