Use cases of Supplier in java 8
Introduction:
Supplier<T> is a functional interface in the Java ,with one abstract method named get().
Which will return an instance of T. In general we can say Supplier is a factory that keeps on
giving without expecting any input.
Syntax.
public abstract T get(); We already know that for any abstract method of functional interface we can implement using lamda expression.
Eg: Supplier<Exception> exceptionFactory = () -> new RuntimeException("error");
When we execute above statement RuntimeException instance not created by the JVM why?
lamda expressions are lazy until unless we invoke the method of functional interface it will not evaluated. so when we call exceptionFactory.get() then only exception object will create by the jvm.
RuntimeException runtimeException = exceptionFactory.get();
LetUs see use cases:
Case 1: Avoid Race Condition.
If we observe getApplicationContext() method we can understand that we are assigning new instance of ApplicationContext if its reference is null. In multi threaded environment its fail to avoid that we have to use synchronized but it has some limitations like there is a possibility of the race condition.
Solution:
If we observe above code we 've take care of the race condition and created instance lazily at the same time ,avoided null checks.
Case 2: If We provided studentId and expecting data from the repository ,If it's not found we have to create exception.
As per above snapshot select() taking studentId as input and passing to studentRepo ,in case not found in DB for the same, then it has to create exception and throw else returns the Student model instance which is converted from entity instance using helper method called modelMapper.
Happy Learning :)
Comments
Post a Comment