Fix synchronization

This commit is contained in:
Andrea Cavalli 2022-01-13 15:56:12 +01:00
parent d24eecca2b
commit 0a896dce38

View File

@ -60,13 +60,12 @@ 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 = new ReaderThread(updatesSupplier, this);
@ -77,14 +76,14 @@ public class DefaultBotSession implements BotSession {
handlerThread.setName(callback.getBotUsername() + " Telegram Executor"); handlerThread.setName(callback.getBotUsername() + " Telegram Executor");
handlerThread.start(); handlerThread.start();
} }
@Override
public synchronized void stop() {
if (!running.get()) {
throw new IllegalStateException("Session already stopped");
} }
running.set(false); @Override
public void stop() {
if (!running.compareAndSet(true, false)) {
throw new IllegalStateException("Session already stopped");
}
synchronized (this) {
if (readerThread != null) { if (readerThread != null) {
readerThread.interrupt(); readerThread.interrupt();
@ -98,6 +97,7 @@ public class DefaultBotSession implements BotSession {
callback.onClosing(); callback.onClosing();
} }
} }
}
public void setUpdatesSupplier(UpdatesSupplier updatesSupplier) { public void setUpdatesSupplier(UpdatesSupplier updatesSupplier) {
this.updatesSupplier = updatesSupplier; this.updatesSupplier = updatesSupplier;