문제

I have a class that uses static methods to wrap remote API calls.

Generally speaking, I don't want my API server to "listen" for these calls all the time, but instead only listen when the class is being used by a program. So I need a way to tell the server to "wake up" when the class gets loaded (how I send the "wake up" message is irrelevant).

I know that I can wake the server up when the first class method is invoked, but I want it to be ready as soon as the class is loaded into a running program (even if it is loaded lazily).

Also, it would be nice to know when the class is no longer used, so I can tell the server to go back to sleep.

Basically, I'm looking for a "constructor" and a "finalizer" of an entire class. Can this be done?

EDIT: A very important thing I forgot to mention, I can't have the user manually initialize/finalize the class using public static methods or anything like that. The class needs to feel like a regular native class.

도움이 되었습니까?

해결책

You can use a Static Initialization Block:

class YourClass {
    static {
        System.out.println("I got loaded!");
    }
}

This will be called at the moment the class gets loaded by the JVM.

For the unloading part, a way (neccessarilly not the best) is to start a timer in the static initializer in which you close the resources after a certain time of no usage. Usage would be indicated by a constructor being called or something like that, but it might be tricky to implement with concurrency issues.

Another way could be to write a custom Classloader.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top