#536 Thread-Safe Callback Scheduler

Companies:
Yandex
Themes:
JavaConcurrencyPractice

A test and an interface are given. Implement a thread-safe scheduler. Executors must not be used.

package ru.artem.papyan.yahello.util;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import ru.artem.papyan.yahello.util.impl.CallbackSchedulerImpl;

import java.time.Instant;

import static org.junit.jupiter.api.Assertions.assertTrue;

class CallbackSchedulerTest {

    private CallbackScheduler scheduler;

    private static class CallbackResult {
        boolean isDone = false;
    }

    @BeforeEach
    void setUp() {
        scheduler = new CallbackSchedulerImpl();
    }

    @AfterEach
    void tearDown() throws Exception {
        scheduler.close();
    }

    @Test
    void testSimple() throws InterruptedException {
        final CallbackResult result = new CallbackResult();

        scheduler.schedule(
                () -> {
                    synchronized (result) {
                        result.isDone = true;
                        result.notify();
                    }
                },
                Instant.now().plusSeconds(2)
        );

        synchronized (result) {
            result.wait();
            assertTrue(result.isDone);
        }
    }
}
package ru.artem.papyan.yahello.util;

import java.time.Instant;

public interface CallbackScheduler extends AutoCloseable {
    void schedule(Runnable callback, Instant when);
}

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