VOOZH about

URL: https://www.geeksforgeeks.org/java/collections-synchronizedset-method-in-java-with-examples/

⇱ Collections synchronizedSet() method in Java with Examples - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Collections synchronizedSet() method in Java with Examples

Last Updated : 22 Oct, 2025

In Java, the Collections.synchronizedSet() method creates a thread-safe (synchronized) Set backed by a specified set, allowing safe concurrent access by multiple threads.

  • Thread Safety: All operations on the returned set are synchronized.
  • Iteration: Iterating over the synchronized set must be done inside a synchronized block to avoid ConcurrentModificationException.

Syntax

public static <T> Set<T> synchronizedSet(Set<T> s)

  • Parameters: s is the set to be wrapped in a synchronized (thread-safe) set.
  • Return Value: Returns a synchronized view of the specified set.

Example 1: Synchronized Set of Strings


Output
Original Set: [1, 2, 3]
Synchronized Set: [1, 2, 3]

Explanation:

  • Creates a normal HashSet and wraps it with Collections.synchronizedSet().
  • Both original and synchronized sets contain the same elements and are now thread-safe

Example 2: Synchronized Set of Integers


Output
Original Set: [100, 200, 300]
Synchronized Set: [100, 200, 300]

Explanation:

  • Demonstrates creating a synchronized set with integer values.
  • Ensures safe access when multiple threads work with the set.

Example 3: Iterating Over a Synchronized Set


Output
Red
Blue
Green

Explanation:

  • Iteration over a synchronized set must be done inside a synchronized block.
  • Prevents ConcurrentModificationException when accessed by multiple threads.

Example 4: Multi-threaded Access


Output
Thread-1 added: 1
Thread-1 added: 2
Thread-2 added: 1
Thread-2 added: 2

Explanation:

  • Multiple threads can safely add elements to a synchronized set without conflicts.
  • Each operation on the set is automatically synchronized.
Comment