I understand that Suppose we have to make ArrayList as a thread safe class, then, should we make all methods as synchronized or only add methods should be synchronized? I understand we have Collections.synchronizedList() method to make arraylist as thread safe but I would like to understand how we will make it on our own.
First you should remind yourself of what "thread-safe" means. Next, for each method consider what has to be done to make it thread-safe. For methods which use the internal state of your ArrayList class, consider how the state could be affected by other threads while the method is using the internal state.
Vaibhav Gargs wrote:If we make all the methods as synchronized, then, won't it solve the purpose?
Synchronized is a tool. A tool that will enable calls to be atomic. Atomic calls does not mean thread safe.
It is not a magic bullet. You have to use correctly. Multiple calls on the ArrayList, multiple calls on the elements. etc. have to be taken care of. Thread safety is not a fire and forget thing. It has to be part of your application design, etc.