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
public synchronized void start() {
if (running.get()) {
public void start() {
if (running.compareAndSet(false, true)) {
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);
readerThread.setName(callback.getBotUsername() + " Telegram Connection");
readerThread.start();
handlerThread = new HandlerThread();
handlerThread.setName(callback.getBotUsername() + " Telegram Executor");
handlerThread.start();
handlerThread = new HandlerThread();
handlerThread.setName(callback.getBotUsername() + " Telegram Executor");
handlerThread.start();
}
}
@Override
public synchronized void stop() {
if (!running.get()) {
public void stop() {
if (!running.compareAndSet(true, false)) {
throw new IllegalStateException("Session already stopped");
}
synchronized (this) {
running.set(false);
if (readerThread != null) {
readerThread.interrupt();
}
if (readerThread != null) {
readerThread.interrupt();
}
if (handlerThread != null) {
handlerThread.interrupt();
}
if (handlerThread != null) {
handlerThread.interrupt();
}
if (callback != null) {
callback.onClosing();
if (callback != null) {
callback.onClosing();
}
}
}