konsoletyper / teavm

Compiles Java bytecode to JavaScript, WebAssembly and C
https://teavm.org
Apache License 2.0
2.65k stars 265 forks source link

Surprising behavior with Thread.sleep() in a synchronized method #969

Open ScraM-Team opened 1 week ago

ScraM-Team commented 1 week ago

I have just started trying out recent versions of TeaVM, running some tests of threading and synchronization. I have a test which runs several threads in parallel, all calling a synchronized method printing messages. The first batch of threads do not pause at all. The second batch of threads uses sleep() to pause between messages.

Surprisingly (at least to me), the second batch does not print out all of the messages. At some point sleep() does not return. Is there a better way to pause threads in TeaVM?

This is the class in question.

public class Client {

  public static void main(String[] args) {
    startThreads(false);
    startThreads(true);
  }

  public static void startThreads(boolean sleep) {
    for (int i = 0; i < 2; i++) {
      final int id = i;
      new Thread(() -> {
        printMessages(id, sleep);
      }).start();
    }
  }

  public synchronized static void printMessages(int id, boolean sleep) {
    for (int j = 0; j < 2; j++) {
      System.out.println((sleep ? "sleep on  " : "sleep off ") + id + ": " + j + "  @" + System.currentTimeMillis());
      if (sleep) {
        try {
          System.out.println("sleep starting...");
          Thread.currentThread().sleep(100L);
          System.out.println("sleep complete");
        } catch (InterruptedException ex) {
          System.out.println("interrupted " + id);
        }
      }
    }
  }
}

This is the console output:

sleep off 0: 0  @1731270744182
sleep off 0: 1  @1731270744183
sleep off 1: 0  @1731270744183
sleep off 1: 1  @1731270744184
sleep on  0: 0  @1731270744184
sleep starting...
sleep complete
sleep on  0: 1  @1731270744285
sleep starting...
sleep complete
sleep on  1: 0  @1731270744386
sleep starting...

Thank you!

konsoletyper commented 6 days ago

@ScraM-Team what backend do you mean? JavaScript?

ScraM-Team commented 5 days ago

Yes, JavaScript backend.