Я новичок в многопоточности.Я пытался сохранить список объектов в базе данных SQL с помощью хранилища CruD.но я получаю исключение нулевого указателя в операции сохранения.Ниже мой код и исключение.Класс потока
public class PrescriptionThread implements Runnable{
private MedicineService medServ = new MedicineService();
private Presciption pres ;
public PrescriptionThread(Presciption pres) {
this.pres = pres;
}
@Override
public void run() {
medServ.savePrescription(pres);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Класс обслуживания
@Service
public class MedicineService {
@Autowired
private PrescriptionRepository presRepo;
public void storePrescription(List<Presciption> payload) {
ExecutorService executorService = Executors.newFixedThreadPool(5);
for (Presciption presciption : payload) {
Runnable runnable = new PrescriptionThread(presciption);
executorService.execute(runnable);
}
executorService.shutdown();
while(!executorService.isTerminated()) {}
}
public synchronized void savePrescription(Presciption pres) {
presRepo.save(pres);
}
}
Репозиторий
@Repository
public interface PrescriptionRepository extends CrudRepository<Presciption, Integer> {
}
Я получаю исключение в presRepo.save (pres);
Exception in thread "pool-1-thread-3" Exception in thread "pool-1-thread-1" Exception in thread "pool-1-thread-2" java.lang.NullPointerException
at com.cerner.api.service.MedicineService.savePrescription(MedicineService.java:86)
at com.cerner.api.util.PrescriptionThread.run(PrescriptionThread.java:16)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)
Если я не использую нить и просто говорю
for (Presciption presciption : payload) {
presRepo.save(pres);
}
Он работает нормально, и я могу сохранить его в БД.Но я хочу реализовать поток.Заранее спасибо.