Part 6 of 6 · 2 min read
Exercises
Easy
Easy 1: Write it three ways (20 minutes)
Write a Counter singleton as a public field, as a static factory and as an enum. Call next() twice on each.
Done when: all three print 1 then 2.
Hint
The enum has a single constant named INSTANCE.
Easy 2: Run the holder (20 minutes)
Type the Holder class and print getInstance() == getInstance().
Done when: it prints true and you can say when the constructor ran.
Hint
The nested class loads on first use of getInstance.
Easy 3: Spot the hidden dependency (20 minutes)
Write a method that reads Config.INSTANCE inside its body. Rewrite it so that the config is a parameter.
Done when: both versions exist and you say which one is easier to test.
Hint
The parameter makes the dependency visible in the signature.
Medium
Medium 1: Break the unsafe one (45 minutes)
Run the unsafe lazy singleton with eight threads and a short sleep in the constructor. Count how many times it is built.
Done when: you see a count above 1, and the synchronized version shows 1.
Hint
Use a CountDownLatch so that all threads start together.
Medium 2: Make a logger singleton (45 minutes)
Write a Log enum singleton with info(String) that stores lines in a list and lines() that returns a copy.
Done when: two classes write to it, and one test reads both lines.
Hint
Return List.copyOf from lines().
Medium 3: Replace with injection (45 minutes)
Change a class that calls Log.INSTANCE into one that receives a Logger interface. Write a test with a fake.
Done when: the test checks a line without touching the global.
Hint
The fake stores lines in a list.
Hard
Hard 1: Serialization break (90 minutes)
Write a serializable singleton with a public field and show that deserializing makes a second instance. Fix it with readResolve. Then replace it with an enum.
Done when: you show false, then true after the fix, and a note says why the enum needs no fix.
Hint
readResolve returns the field.
Hard 2: Compare four ways (90 minutes)
Write the same lazy singleton with synchronized, eager, holder and enum. Compare thread-safety, laziness and testability.
Done when: a table of four rows and three columns is complete with a recommendation.
Hint
Holder is lazy without a lock on the normal path.
Hard 3: One per thread (90 minutes)
Using the static factory form, change getInstance() to return one instance per thread (use ThreadLocal). Show that the API did not change.
Done when: two threads get different objects, and the same thread gets the same object twice.
Hint
ThreadLocal.withInitial does the job.