I have an CopyOnWriteArrayList as my code should be thread safe. List friuts = new CopyOnWriteArrayList<>();
I don't want to have duplicate friuts in list I cannot use Set as I want to have insertion order as well. I have written this code
public boolean add(String friut) {
synchronized (friuts) {
if (friuts.contains(friut)) {
return false;
}
friuts.add(friut);
}
return true;
}
As I know is CopyOnWriteArrayList already concurrent. So adding CopyOnWriteArrayList.add within synchronized block doesn't seems to be a good idea to me. Is there any other better solution?
Use the addIfAbsent()
method:
CopyOnWriteArrayList<String> fruits = new CopyOnWriteArrayList<>();
public boolean add(String fruit) {
fruits.addIfAbsent(fruit);
}