#377 Non-Deterministic Order of Asynchronous Exercises

Companies:
Aston
Themes:
JavaConcurrencyCode Review

What will be printed?

public class Main {
    public static void main(String[] args) throws InterruptedException {
        new Test().print();
    }
}

class Test {
    private Object object = new Object();

    public void print() throws InterruptedException {
        CompletableFuture.runAsync(() -> {
            synchronized (object) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("1");
            }
        });

        synchronized (object) {
            System.out.println("2");
        }

        CompletableFuture.runAsync(() -> {
            synchronized (object) {
                System.out.println("3");
            }
        });
    }
}

Question review

Mentor
Answer as you would in a real interview. I’ll ask follow-up questions, then compare your answer with the reference answer and show your accuracy as a %.
Sign in to start the dialogue The mentor keeps the context of the current question and your previous messages.
Sign in