Preloading java classes/libraries at jar startup?

為{幸葍}努か 提交于 2019-12-18 05:55:46

问题


I've written a Thrift server in Java to take advantage of a specific Java package/library, but I'm not a java programmer.

The problem is; I'm seeing a time-out for the first RPC call to the server. Subsequest requests are executed without any issues, and its only affecting clients written in certain (but essential) languages.

My current thought is that the server times-out on the response because upon first call it has to load all the libraries required for the request. Some Thrift client implementations must be handling the time-out better than others, possibly keeping the request open a little longer.

Is there a way in java to preload the libraries I'm using when I first initiate the .jar file so there isn't a delay on the first request?

Solution: I got around the problem (and some further ones raised) by increasing the timeout from the thrift client(s). However, I've implemented the static/Class.forName answer also to help things along, which works great. Thanks!


回答1:


You could run a load before the server becomes live. You haven't specified how you're loading the server, the classes, and what the environment is, but you can take advantage of the fact that a class static initializer will run when the class is loaded. So, if you're running from a "main" method, your class could look something like this

public class Foo {

   static {
     //this will be run when the class is loaded
     try { Class.forName("fully.qualified.class.name.that.i.want.to.Load"); }
     catch ...
   }

   public static void main (string args[])
   {
    //run my server...
   }
}



回答2:


One thing you might want to try is writing a simple client inside of the Java server itself. This client does nothing but call some method in the server when it starts up, forcing the classes to be loaded. After this little client gets a result (or callback), then it puts the server into an "accessible by the outside world" state.




回答3:


I suggest faking a connection just before opening up the server. That will ensure that (most) relevant lazy initialisation will have been performed.



来源:https://stackoverflow.com/questions/677739/preloading-java-classes-libraries-at-jar-startup

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!