1

I came across a problem while working with stateless EJB. I want that a particular static method should be used in that EJB but this method is so important and it has static dependency.

As we know instances of stateless session beans are created as per requirements (one or many). So how can I be sure that all the EJB are using a single copy of that static method. I am not sure but I think every different class who use a static method will load different copy of class and then execute a different copy of the static method.

And I can't rely on singleton EJB as it not guaranty that only one copy will remain because if more than one JVM required by server. Different copy of singleton EJB will be in to existence in different JVM.

Thanks in advance.

1 Answers1

1

Static methods are one per class, even if you create thousands of instance of that class all of them will see just one copy of your static method.

Now as per Spec you should not have static methods in your EJB, you should consider moving this as part of utility if you want it static, or else make it non static.

From the Spec:

EE.5.2.3 Annotations and Injection

As described in the following sections, a field or method of certain container-managed component classes may be annotated to request that an entry from the application component’s environment be injected into the class. Any of the types of resources described in this chapter may be injected. Injection may also be requested using entries in the deployment descriptor corresponding to each of these resource types. The field or method may have any access qualifier (public, private, etc.). For all classes except application client main classes, the fields or methods must not be static.

mprabhat
  • 20,107
  • 7
  • 46
  • 63
  • 1
    I wonder why it says they "must not be static". Who cares if they're static? Even in standard Java, static methods are kind of a black sheep: being procedural, not object-oriented, it doesn't really matter where you put them. Programmers organize static methods into classes, but because they don't operate on object state the choice is somewhat arbitrary. – DavidS Dec 10 '15 at 19:22
  • I recently learned that "they must not be static" because static methods do not participate in container-managed transactions, AOP, security, etc. If we then ask "Why don't static methods participate in AOP, etc." I think it's related to how EJB/CDI uses proxies to do its job: proxies are often implemented by implementing interfaces or extending classes, which doesn't work on static methods (similar to [Mockito](https://stackoverflow.com/questions/4482315/why-does-mockito-not-mock-static-methods)). – DavidS Mar 14 '16 at 23:56