Junior — Middle
How to decide whether to create a new instance of the database-related library for each incoming request in the controller?
sobes.tech AI
Answer from AI
The decision to create a new instance of a library for database operations for each incoming request depends on several factors:
- Thread safety: If the library is not thread-safe, it is better to create a new instance for each request to avoid conflicts.
- Resource intensity: If creating an instance is costly, consider using an object pool or a singleton with caution.
- Request lifecycle: In web applications, the "per-request" pattern is often used, where a separate database context (e.g., EntityManager in JPA) is created for each request.
- Transaction management: A new instance allows isolating transactions and avoiding unwanted side effects.
In Java applications using Spring, it is common to create a bean with a "request" scope or use @Transactional to manage the lifecycle and create a new EntityManager instance per request. If the library supports pooling, it can be used for optimization.
Therefore, it is preferable to create a new instance for each request if it is not too costly and ensures data safety and isolation.