开发者

Loading the class only once

开发者 https://www.devze.com 2023-01-15 21:16 出处:网络
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.
  1. I am implementing an service class which uses the services of the third party providers.

  2. 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 && m开发者_如何学JAVAultiply.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


You can implement the singleton pattern. One option is using an enum:

public enum Service {
    INSTANCE;

    private ThirdPartyService service = new ThirdPartyService();

    public ThirdPartyService getService() {
        return service;
    }
}

But don't overuse that pattern, because it makes it hard to unit-test your code.


Go for Spring.
Make a bean entry and keep it singleton [which is by default]
It will create an object of that class once when context is initialized then it won't touch the class and your purpose will get solved.


You could also check out OSGi, which has a service model and will take care of all class loading for you. You can also combine it with Spring to get the benefits from both worlds.

0

精彩评论

暂无评论...
验证码 换一张
取 消