What is the real use case for @Stateless compared to @Singleton in EJB

if I understand EJB correctly, @Singleton is actually the same as Singleton in simple Java, as well as singleton in spring β†’ one instance, each call goes through the same instance at the same time. @Stateless declares a bean that can (but should not) have multiple instances with the restriction that only one call can be in the instance at a time. Correct Sofar? This remains for me on the model of servlet programming: in theory, servlet containers are allowed to create several copies of the servlet, in practice I have not seen any servlet containers for this. Therefore, assuming that I do not have REALLY LIMITED resources, such as doors, windows or printers in my code (and if I did, I could still allow it with queues, etc.) What is a REAL example where using @Stateless is advantageous compared to using @Singleton.

Regards Leon

+4
source share
2 answers

Stateless implies that a bean is thread safe. This is because the bean does not use state-dependent code. This means that running any of its methods will not affect the future actions of these methods.

An example of a stateless class is a class that does addition and subtraction. All necessary parameters are passed to the method. Performing addition or subtraction does not change the way these methods work on subsequent calls. This means you don’t have to worry about concurrency with the class.

Singleton is commonly used for a class that is very expensive to create, such as connecting to a database. You do not want each class to create a new database connection each time they need to use the database, so you run it once when the program starts. Single unity does not necessarily mean that the class is thread safe (although this is absolutely necessary).

So idle means that the class is thread safe.

Singleton refers to the fact that a class is created only once. While this largely implies that the class is (AND IT MUST BE) thread safe, it does not directly imply it, as stateless does.

0
source

You can have multiple instances of a dumb bean to increase throughput.

On the other hand, there is only one instance of a singleton. The reason for this is, as a rule, the sharing of state in the application area, serialization of access to resources, etc., And this implies blocking or synchronization.

So, if you don’t actually have a single, then use a static bean.

If you have a "single single post", there is no difference. But if you read "singleton", it has special meaning by convention (= there must be a reason for using the singleton pattern).

0
source

Source: https://habr.com/ru/post/1486301/


All Articles