THINK FIRST·CODE LATER

← All labs

Resilient tutor: fallback and circuit breaker

Problem

Implement Buddy's resilience layer with dependency inversion. Define an interface Tutor with String answer(String question) throws Exception, and two implementations simulating providers. Then write a ResilientTutor that uses a primary and a secondary tutor with a circuit breaker on the primary.

Input: lines P S question... until the end of input, where P and S are the status of the primary and secondary provider for that request: UP (answers) or DOWN (throws an exception).

Behaviour for each question:

  1. If the breaker is open, skip the primary (it counts one skipped request). After 2 skipped requests the breaker becomes half-open: the next request tries the primary once.
  2. Otherwise try the primary. If it answers, print [primary] <question> and reset the failure count (breaker closed). If it fails, count a consecutive failure; after 3 consecutive failures — or after a failed half-open trial — the breaker opens (and the skip counter starts at 0).
  3. If the primary was skipped or failed, try the secondary: [secondary] <question>; if it also fails print [offline] Buddy is offline - please post "<question>" on the board.

After each line, if the breaker changed state, print breaker: OLD -> NEW (states CLOSED, OPEN, HALF_OPEN). At the end print Primary: a, Secondary: b, Offline: c.

Input:

DOWN UP q1
DOWN UP q2
DOWN DOWN q3
UP UP q4
UP UP q5
UP UP q6

Output:

[secondary] q1
[secondary] q2
[offline] Buddy is offline - please post "q3" on the board
  breaker: CLOSED -> OPEN
[secondary] q4
[secondary] q5
  breaker: OPEN -> HALF_OPEN
[primary] q6
  breaker: HALF_OPEN -> CLOSED
Primary: 1, Secondary: 4, Offline: 1

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

s6-3-data-1.txt

DOWN UP q1
DOWN UP q2
DOWN DOWN q3
UP UP q4
UP UP q5
UP UP q6
What your program must print for s6-3-data-1.txt
[secondary] q1
[secondary] q2
[offline] Buddy is offline - please post "q3" on the board
  breaker: CLOSED -> OPEN
[secondary] q4
[secondary] q5
  breaker: OPEN -> HALF_OPEN
[primary] q6
  breaker: HALF_OPEN -> CLOSED
Primary: 1, Secondary: 4, Offline: 1

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < s6-3-data-1.txt

Windows PowerShell does not understand <:

Get-Content s6-3-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.