In Java, a currying function is thread-safe or not

47 Views Asked by At

As far as I understand, a simple java.util.Function should be thread-safe since it takes one parameter, processes it, and returns something. However, what about a currying function?

Let's consider a scenario where I define a private function (which is currying and complex) in a service singleton. Any request handled would call the currying function on its thread:

private Function<String, Function<String, Function<LocalDate, Function<LocalDate, Function<String, Function<Integer, Map<String, Object>>>>>>> curryingFunc = id -> path -> startDate -> endDate -> sortKey -> sortOrder -> {
    Map<String, Object> map = new HashMap<>();
    map.put("id", id);
    map.put("path", path);
    map.put("startDate", startDate);
    map.put("endDate", endDate);
    map.put("sortKey", sortKey);
    map.put("sortOrder", sortOrder);
    return map;
};

Is it possible that a request on thread-1 just finished setting the id as 'apple' in the map and is about to return the map, but somehow a request on thread-2 just called the function and set the id to 'broccoli', thus causing a race condition problem?

In another scenario, what if it's not taking parameters and composing them as a map but calling some other function? For example:

private Function<String, Function<String, Function<LocalDate, Function<LocalDate, Function<String, Function<Integer, UserData>>>>>> curryingFunc = id -> path -> startDate -> endDate -> sortKey -> sortOrder -> {
    return userDataRepository.find(id, path, startDate, endDate, sortKey, sortOrder);
};
0

There are 0 best solutions below