Fix synchronization

This commit is contained in:
Andrea Cavalli 2022-01-13 15:56:12 +01:00
parent d24eecca2b
commit 0a896dce38
1 changed files with 23 additions and 23 deletions

View File

@ -60,42 +60,42 @@ public class DefaultBotSession implements BotSession {
} }
@Override @Override
public synchronized void start() { public void start() {
if (running.get()) { if (running.compareAndSet(false, true)) {
throw new IllegalStateException("Session already running"); throw new IllegalStateException("Session already running");
} }
running.set(true); synchronized (this) {
lastReceivedUpdate = 0;
lastReceivedUpdate = 0; readerThread = new ReaderThread(updatesSupplier, this);
readerThread.setName(callback.getBotUsername() + " Telegram Connection");
readerThread.start();
readerThread = new ReaderThread(updatesSupplier, this); handlerThread = new HandlerThread();
readerThread.setName(callback.getBotUsername() + " Telegram Connection"); handlerThread.setName(callback.getBotUsername() + " Telegram Executor");
readerThread.start(); handlerThread.start();
}
handlerThread = new HandlerThread();
handlerThread.setName(callback.getBotUsername() + " Telegram Executor");
handlerThread.start();
} }
@Override @Override
public synchronized void stop() { public void stop() {
if (!running.get()) { if (!running.compareAndSet(true, false)) {
throw new IllegalStateException("Session already stopped"); throw new IllegalStateException("Session already stopped");
} }
synchronized (this) {
running.set(false); if (readerThread != null) {
readerThread.interrupt();
}
if (readerThread != null) { if (handlerThread != null) {
readerThread.interrupt(); handlerThread.interrupt();
} }
if (handlerThread != null) { if (callback != null) {
handlerThread.interrupt(); callback.onClosing();
} }
if (callback != null) {
callback.onClosing();
} }
} }