- I am implementing an service class which uses the services of the third party providers.
- User will interact with the Service class to get the service of the service provider.
My requirement:
I want to load the service class only once( or it persist for long time in memory say 2 Hr.).
My question:
How can I check that this service class is loaded only once?
If it is loaded each time an request is made so is there any way to them persist in the memory?
Here is the code of my Service class
package com.example; import com.example.spi.Multiplication; import java.util.Iterator; import java.util.ServiceLoader; public class MultiplicationService implements Multiplication{ private static MultiplicationService service; private ServiceLoader loader; public static int no=0; private MultiplicationService() { loader = ServiceLoader.load(Multiplication.class); } public static synchronized MultiplicationService getInstance() { if (service == null) { service = new MultiplicationService(); } return service; } public int getMultiplication(int a,int b){ int result = 0; try { Iterator multiply = loader.iterator(); while (result == 0 && multiply.hasNext()) { Multiplication d = multiply.next(); result = d.getMultiplication(a,b); System.out.println("Result is : "+ result); } } catch (Exception serviceError) { result = 0; serviceError.printStackTrace(); } return result; } }
Thanks