0

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).

xragons
  • 13
  • 5

1 Answers1

2

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.

Prashant
  • 4,775
  • 3
  • 28
  • 47
  • So just to be safe I should use read lock? I don't quite understand the behavioral parameters side effects. Ty. – xragons Aug 10 '18 at 22:36
  • As per documentation, its not a good idea to use any sort of mutable variable in your lambda expression. Using read lock defeats the purpose of using streams that work in pipeline. There is no one to stop you from using read locks though. Streams bring in (in a way) functional paradigm to Java. One of the most important concepts there to enforce immutability. You are better off using normal for loop without performance loss if you are using locks. The documentation (ref. the answer) has a very detailed section on side effects. – Prashant Aug 13 '18 at 03:33