Skip to content
Advertisement

Spring boot JPA repository passed to another thread not working

I have an autowired jpa repository object working. However, I need to use it to add rows into the database from multiple threads.
Though, after passing it to another thread, it fails. Code structure

JavaScript

However, doing a dbRepository.save() from a thread safe class, I get error cause: java.lang.IllegalStateException: org.springframework.context.annotation.AnnotationConfigApplicationContext@41330d4f has been closed already

detailedMessage: Error creating bean with name 'spring.datasource-org.springframework.boot.autoconfigure.jdbc.DataSourceProperties': Could not bind properties to 'DataSourceProperties' : prefix=spring.datasource, ignoreInvalidFields=false, ignoreUnknownFields=true

Stacktrace:

JavaScript

How can I use the spring boot repository object across multiple threads ?

Advertisement

Answer

The problem is that your run() method just schedules the tasks to be executed, but does not wait for their completion. This what is happening:

  1. new SpringApplicationBuilder(Application.class) You are creating a new application context with the command line runner Application
  2. .run(args) Then you initialize and execute your application context’s run() method
  3. The run() method schedules the tasks to be executed and exists immediately:
JavaScript
  1. Because run() terminated, spring assumes that the application has finished and calls .close(); Thus closing the application context and making it impossible to use any spring features such as repositories.

  2. The scheduled tasks get executed, but the context was already closed, thus they fail and throw the exception.

The solution is to wait for the tasks’ completion before exiting from the run method. As your example is too minimal, this is just an example. Alternatively you can use other methods to wait for the completion of the tasks such as CountDownLatch , etc, without having to shutdown the thread pool:

JavaScript

ExecutorService::shutdown javadoc

ExecutorService::awaitTermination javadoc

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement