CSE Roadmap

Core tier · about 3 hours · 6 parts

Part 6 of 6 · 2 min read

Exercises

Easy

Easy 1: Name the parts (20 minutes)

A phone shows a notification when a message arrives. Name the subject, the observers and the event.

Done when: you have a subject, two possible observers and an event record.

Hint

The event says what changed, such as the sender and the text.

Easy 2: Run the board (20 minutes)

Type the RoomBoard code. Subscribe a screen and a mail lambda, set A1 busy, unsubscribe mail, set A1 free.

Done when: the log shows the three lines of section 2.

Hint

The mail lambda can add a string to the log.

Easy 3: Spot the leak (20 minutes)

Write a short note on what happens to a screen object that is closed but never unsubscribed.

Done when: the note says why the board still holds it and how to fix it.

Hint

The board holds a strong reference to the observer.

Medium

Medium 1: Stock alerts (45 minutes)

Write a PriceFeed that notifies observers of a new price. Add an observer that alerts only when the price rises above a limit.

Done when: three price changes give exactly one alert.

Hint

Keep the limit in the observer.

Medium 2: One-shot listener (45 minutes)

Write a listener that unsubscribes itself after the first event. First use a plain ArrayList and see the exception. Then use CopyOnWriteArrayList.

Done when: you show the exception and the fixed run.

Hint

Removing during iteration is the cause.

Medium 3: Safe notify (45 minutes)

Make the set loop catch an exception from one observer and still call the rest. Log the failure.

Done when: a throwing observer does not stop the other two.

Hint

A try and catch inside the loop.

Hard

Hard 1: Pull version (90 minutes)

Rewrite the board as a pull version. Observers receive only the board and ask isFree(room). Compare with push.

Done when: a table lists lines changed, coupling and extra calls for both.

Hint

The observer gets a reference to the subject.

Hard 2: Observers under threads (90 minutes)

Run the board with four threads calling set, and observers that add to a shared list. Find the data race and fix it.

Done when: a run of 1000 updates gives the right count of log entries.

Hint

The shared list needs a thread-safe type.

Hard 3: A cascade (90 minutes)

Build two subjects where each has an observer that updates the other. Show the infinite loop, then break it with a rule such as "ignore if the value did not change".

Done when: the loop is shown, stopped, and a test proves it stops.

Hint

Compare the new value to the old one before notifying.