问题
I have an MDB EJB, with static block inside it. I used the static block to initialize some components only once at the first time the application runs (i.e at deployment). The MDB EJB is deployed on a separate sever (My_Server) other than the Admin_Server.
The problem is that the static block is called twice!
- The first time: just after deploying the MDB EJB (tageted to the My_Server).
- The second time: after the JMS queue (that the MDB is associated with) receives a message.
Also, I printed the server name and the pid, and they are same in both:
System.out.println("server name: " + System.getProperty("weblogic.Name"));
System.out.println("pid: " + ManagementFactory.getRuntimeMXBean().getName().split("@")[0]);
I also noticed some weird behaviors. Basically, I attached a Shutdown Hook (from inside the static block) to send me email on shutdown of the application.
- I got notified once I shutdown the My_Server.
- I got notified also once I shutdown the Admin_Server.
How can I solve this issue?
Some extra info:
Weblogic version: 10.3.0
EJB version: 3.0
回答1:
This only happens when you have multiple classloaders. I would not have static initializers in an EJB, rely on either EJB lifecycle hooks or export the initializer into an unmanaged class.
EJB 3.1 added annotations like @Singleton and @Startup, but unfortunately in 3.0 you are stuck with provider-based solutions for these guarantees.
Admin vs regular server behavior is quite common as WebLogic usually deploys to both. See this page for more information.
For Weblogic shutdown hooks check this documentation page.
回答2:
Yes, the only way that you can get a static initializer executed more than once is if you actually have loaded two distinct copies of the class. And that can only happen if you have two different classloader that both load the class.
The way to prevent this is to arrange that the classes in question are loaded by a common ancestor class loader of the two classloaders. I don't know how you would do this with Weblogic, but for Tomcat you would put the relevant JAR files into a designated common library directory that is shared by all webapps running in the container.
来源:https://stackoverflow.com/questions/14433978/static-block-is-called-twice-maybe-multiple-class-loaders