How to synchronize java streams

Viewed 132

I have a mail service in which there are two entities: the message and the sender. First of all, I set up a connection to my mail and am trying to pull out information about SMS. Separately in the senders table, separately their messages. To do this, I try to use a common Service object, and I share tasks. task one is to write the sender to the table. Task number two is to save messages from this addressee .In a separate table. Therefore, the first thread does task 1, the second task 2. But everything does not happen as I expect. The first thread works out - the second and the threads hang , and then nothing happens. Help me figure it out

@Component
public class Service {

    @Autowired
    private SenderRepository senderRepository;
    @Autowired
    private MsgRepository msgRepository;
    @Autowired
    private MessageConfig messageConfig;
    @Autowired
    private SenderMapping senderMapping;
    @Autowired
    private MsgMappingUtils msgMappingUtils;


    private boolean records = false; // флаг записи в базу
    private Address senderAddress; // адрес отправителя
    private Integer senderId; // id сохранненого отправителя
  //  private ArrayList<Message> groupMessages = new ArrayList<>(); // хранит письма принадлежащие отправителю

    public synchronized void saveMessageRepos() throws Exception {

       // Message[] messages = saveSenderRepos(); // перед сохранением сообщений в бд - записываем информацию об отправителях
        // далее -> записываем содержимое сообщений
        if (records == false) {
            wait();
        }

        else {
            Enum<Folder.currentFolder> currentFolder = Folder.currentFolder.INBOX;
            Flags seen = new Flags(Flags.Flag.SEEN); // флаг прочитанности
            boolean stateFlag = false; // в текущем случае unseen

            Message[] messages = messageConfig.getMessage(currentFolder, seen, stateFlag,senderAddress);

            for (Message message : messages) {
                // достаем из базы отправителя, ищем сообщения которые он отправил
                Msg mes = msgMappingUtils.mapDtoToEntity(message,senderId);
                    msgRepository.save(mes);

            }
            senderAddress = null; // очищаем строку
            records = false;
        }
        notify();
    }

    public synchronized void saveSenderRepos() throws MessagingException, InterruptedException {

        if (records == true) wait();

        else {
            Enum<Folder.currentFolder> currentFolder = Folder.currentFolder.INBOX;
            Flags seen = new Flags(Flags.Flag.SEEN); // флаг прочитанности
            boolean stateFlag = false; // в текущем случае unseen
            HashSet<Address> uniquePersonAddress = messageConfig.getMessage(currentFolder, seen, stateFlag);
            // получаем массив уникальных отправителей
            for (Iterator <Address> iterator = uniquePersonAddress.iterator(); iterator.hasNext();) {
                // очередной отравитель не записан
                Address address = iterator.next();
                Sender sender = senderMapping.mapDtoToEntity(address); // создаем сущность отправителя
                senderRepository.save(sender);
                iterator.remove();
                records = true; // отправитель записан
                senderId = senderRepository.findlastIdSender();
                // получили id сохраненного
                // пользователя
                senderAddress = address;
                break;
            }
            notify();
        }

        }


}
import com.axsoft.mail.services.Service;

public class TwoTask implements Runnable {
    // задача записи сообщений отправителей, которые находятся в БД

        Service service;
        public TwoTask(Service service){
            this.service = service;
        }

        public TwoTask() {
        }

        @Override
        public void run() {
            try {
                service.saveMessageRepos();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

    }
package com.axsoft.mail.services.tasks;

import com.axsoft.mail.services.Service;
import jakarta.mail.MessagingException;

public class OneTask implements Runnable { // задача записи отправителей в БД

    Service service;
    public OneTask(Service service){
        this.service = service;
    }

    public OneTask() {
    }

    @Override
    public void run() {
        try {
            service.saveSenderRepos();
        } catch (MessagingException | InterruptedException e) {
            e.printStackTrace();
        }

    }

}
@SpringBootApplication
public class MailApplication implements CommandLineRunner {

    @Autowired
    Service emailService;
    private Object OneTask;


    public static void main(String[] args) throws MessagingException {
        SpringApplication.run(MailApplication.class, args);

}
@Override
    public void run(String... args) throws Exception {  // выполнение кода при старте
        //emailService.saveMessageRepos();

        OneTask oneTask = new OneTask(emailService);
        TwoTask twoTask = new TwoTask(emailService);

        new Thread(oneTask).start(); // поток который сохраняет в БД отправителей
        new Thread(twoTask).start(); // поток который записывает соответствующие сообщения отправителя в БД,
        // как только  отправитель записан в базу


    }
}
0 Answers
Related