0
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?

Anoop Hallimala
  • 625
  • 1
  • 11
  • 25
  • Lets consider both scenarios? – Anoop Hallimala Sep 13 '19 at 13:43
  • OK. Is this pattern advisable? I see this a lot in the code I'm reviewing. – Anoop Hallimala Sep 13 '19 at 13:46
  • 1
    There isn't anything blatantly wrong with this pattern that I can see. If you need it to be threadsafe and you're not sure about it, you can surround your calls to the function with a lock. – byxor Sep 13 '19 at 13:53
  • I've another question: Every time I call someFunction(someRequest), does it return unique lamdas? Or the same instance? – Anoop Hallimala Sep 13 '19 at 13:59
  • 1
    @AnoopHallimala I'm not sure. You can check this yourself by calling the function multiple times and seeing if `lambda1 == lambda2`. – byxor Sep 13 '19 at 16:03
  • It is slightly different. Test$$Lambda$1/2110121908@75a1cd57 and Test$$Lambda$1/2110121908@3d012ddd. – Anoop Hallimala Sep 16 '19 at 04:50
  • 1
    You have evaluated the particular behavior of an implementation. The general answer is that it is unspecified whether a new object is created or not. Of course, if the captured objects differ, it must create different objects to ensure the correct behavior. But if invoked with the same request, it could produce the same object though it currently doesn’t. See [Does a lambda expression create an object on the heap every time it's executed?](https://stackoverflow.com/q/27524445/2711488). And you can safely assume that if there’s sharing of resources behind the scenes, it will be done thread safe – Holger Sep 18 '19 at 14:08

1 Answers1

0

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.

Anoop Hallimala
  • 625
  • 1
  • 11
  • 25