📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.
🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.
▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube
This is a very useful construct in the multi-threaded programs – when we want to iterate over a set in a thread-safe way without an explicit synchronization.
A CopyOnWriteArraySet that uses an internal CopyOnWriteArrayList for all of its operations.
CopyOnWriteArraySet Class Example
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArraySet;
/**
* This program demonstrates how a CopyOnWriteArraySet works in multi-threading
* context.
*
* @author www.javaguides.net
*/
public class CopyOnWriteArraySetExample {
public static void main(final String[] args) {
final CopyOnWriteArraySet<Integer> set = new CopyOnWriteArraySet<>();
set.add(1);
set.add(2);
set.add(3);
set.add(4);
set.add(5);
final Runnable runnable = () -> {
set.add(4);
set.add(5);
};
final Thread thread = new Thread(runnable);
thread.start();
final Iterator<Integer> iterator = set.iterator();
while (iterator.hasNext()) {
final Integer integer = iterator.next();
System.out.println(integer);
}
}
}
1
2
3
4
5
Comments
Post a Comment
Leave Comment