Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
ScraM-Team opened this issue Nov 10, 2024 · 2 comments
Open

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

ScraM-Team opened this issue Nov 10, 2024 · 2 comments

Comments

@ScraM-Team
Copy link
Contributor

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
Copy link
Owner

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

@ScraM-Team
Copy link
Contributor Author

Yes, JavaScript backend.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants