#536 Thread-Safe Callback Scheduler
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
Sign in to start the dialogue
The mentor keeps the context of the current question and your previous messages.
Sign in
Available with Premium
This is just one of the solutions available with Premium. And more:
- 250+ advanced lectures
- 1300+ practice exercises
- 500+ solutions to problems from real interviews
- Personalized Java Hub certificates
- Expanded access to the AI mentor