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
<code>public boolean add(String friut) {
synchronized (friuts) {
if (friuts.contains(friut)) {
return false;
}
friuts.add(friut);
}
return true;
}
</code>
<code>public boolean add(String friut) {
synchronized (friuts) {
if (friuts.contains(friut)) {
return false;
}
friuts.add(friut);
}
return true;
}
</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?
New contributor
Ahmed Bilal is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
4
Use the addIfAbsent()
method:
<code>CopyOnWriteArrayList<String> fruits = new CopyOnWriteArrayList<>();
public boolean add(String fruit) {
fruits.addIfAbsent(fruit);
}
</code>
<code>CopyOnWriteArrayList<String> fruits = new CopyOnWriteArrayList<>();
public boolean add(String fruit) {
fruits.addIfAbsent(fruit);
}
</code>
CopyOnWriteArrayList<String> fruits = new CopyOnWriteArrayList<>();
public boolean add(String fruit) {
fruits.addIfAbsent(fruit);
}
1