Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java CopyOnWriteArrayList add element if not exists already

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use the addIfAbsent() method:

CopyOnWriteArrayList<String> fruits = new CopyOnWriteArrayList<>();

public boolean add(String fruit) {
    fruits.addIfAbsent(fruit);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading