views:

132

answers:

3

Hello everybody.

Like the title says, i would like to get a thread-safe HashSet using Guava Collections.

Can you help me?

Thanks!

+6  A: 
Set<K> set = Collections.newSetFromMap(new ConcurrentHashMap<K, Boolean>());
Chris Jester-Young
Thanks,i'll try it.
santiagobasulto
Btw, all your points belong to me as i answered this question on the guava mailing list, 8 minutes before it was posted here ;)
Willi
@Willi: If I could assign them to you, I would, because I've already hit my rep cap for the day, so I'm getting absolutely no rep for this answer. :-P
Chris Jester-Young
@Willi You don't!!!! I can't see it! I posted it on the discussion group.
santiagobasulto
You'd think there'd be a little bit more straightforward way of doing this.
ColinD
@Colin: Welcome to Java! If you want straightforward, code in Ruby or Scheme. :-P
Chris Jester-Young
@Colin: it may seem like a monster code. But once you get in the API and familiarize with it, you get amazed how simple it get. It happened to me with the Streams Framework.
santiagobasulto
I'm pretty familiar with most core Java APIs, this trick just strikes me as particularly unintuitive as the best way to accomplish this.
ColinD
+2  A: 

Google Collections had a factory method named Sets.newConcurrentHashSet() for a while.

Its implementation was similar to Chris's suggestion:

public static <E> Set<E> newConcurrentHashSet() {
  return newSetFromMap(new ConcurrentHashMap<E, Boolean>());
}

They had a newSetFromMap() method inside the com.google.common.collect.Sets class (written by Doug Lea with assistance from members of JCP JSR-166). That method was added to java.util.Collections in java 1.6.

It was withdrawn in Google Collections 1.0rc1, since there are plans to better support concurrent sets in Guava (more information here).

This post expands on the use of the "newSetFromMap" method to construct concurrent sets.

eneveu
A: 

This would be the right answer, Using the Sets class from Guava. Anyway the answer from @crhis was good intended.

Sets.newSetFromMap(new ConcurrentHashMap<V, Boolean>());
santiagobasulto