javafunctional-programmingthread-safetypure-function

Can we return Function from a method in a thread-safe way?


private Function<ServiceBean, Mono<SomeResponse>> someFunction(SomeRequest someRequest) {
    return serviceBean -> serviceBean.doSomething(someRequest)
            .next();
}

Is the above method safe?

If I create, say 10 threads, with different type of SomeRequests and call this method at the same time, is it safe to assume there is threadsafety?


Solution

  • Yes, this is thread-safe. But each time someFunction(..) is called, it'll create a new lambda. Even though lamdas are light weight objects, its not a good idea to create a Function like this. Its better to have a BiFunction declared at the class level.