xragons
xragons

Reputation: 13

Stream filter thread safety

I was wonder if I will experience race conditions or concurrency issues with this piece of code:

public User getByName(String name) {
   characters.values().stream().filter(chr -> chr.getName().equalsIgnoreCase(name)).findAny().orElse(null)); 
}

Where `characters is:

private final Map<Integer, Player> characters = new HashMap<>();

Is there a need to use ReentrantReadWriteLock here? Basically this is a type of character storage for my game, where I add and remove the character object. (Via Put/remove).

Upvotes: 0

Views: 1374

Answers (1)

Prashant
Prashant

Reputation: 5393

Streams do not guarantee any thread safety. If you are using a class member (as in your case), you must make sure that you manage threads at your end. However, if you are using local variables in your lambda expression, these variables are not visible to other threads. Also, note that making characters final only guarantee that the variable could not be reassigned. Changes to the map itself could still be made. For more details, you could even have a look at this answer.

EDIT: According to the documentation:

Side-effects in behavioral parameters to stream operations are, in general, discouraged, as they can often lead to unwitting violations of the statelessness requirement, as well as other thread-safety hazards.

The key take away is the use of the term behavioral parameters which implies to state keeping (member variables) of the class.

Upvotes: 2

Related Questions