What thread-safety bug can a naive lazy-loading proxy have, and how would you fix it?
A naive lazy-loading proxy checks 'if the real object reference is null, construct it' without any synchronization. Under concurrent access, two threads can both read the field as null before either one finishes constructing the real object, so both threads construct their own separate instance -- doubling the expensive work and breaking the single-instance caching guarantee the proxy was supposed to provide. The fix is to make the check-and-create sequence atomic, either by synchronizing the entire method, which is simple but serializes every call, or by using double-checked locking with a volatile field, which only pays the synchronization cost on the first call. Which fix makes sense depends on how much concurrent contention the proxy actually expects to see.
Ready to master this question?
Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.
Sign in to generate a response