WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Design Patterns · Intermediate · question 34 of 100

How does the Flyweight pattern interact with the Garbage Collection mechanism in languages like Java and C#?

📕 Buy this interview preparation book: 100 Design Patterns questions & answers — PDF + EPUB for $5

The Flyweight pattern is a software design pattern that aims to minimize memory usage by sharing as much data as possible among similar objects. This is achieved by separating the intrinsic (shared) state and extrinsic (non-shared) state of objects, and storing the intrinsic state in a Flyweight Factory that can be shared by multiple objects.

The Garbage Collection mechanism in languages like Java and C# is responsible for reclaiming the memory used by objects that are no longer referenced by any other object in the program. This mechanism periodically runs in the background, automatically freeing up memory that is no longer in use.

The Flyweight pattern interacts with the Garbage Collection mechanism in two ways:

1. Shared Flyweight objects are not eligible for Garbage Collection until all objects that reference them are also eligible for Garbage Collection. This is because these objects are still being used by other objects and should not be deleted prematurely.

2. Flyweight Factories themselves can be eligible for Garbage Collection if there are no objects that reference them. This can happen if all objects that use the Flyweight Factory to create Flyweight objects are themselves no longer referenced by any other object in the program.

Here’s an example of how shared Flyweight objects are handled by the Garbage Collection mechanism in Java:

// Flyweight Factory class
class FlyweightFactory {
    private static Map<String, Flyweight> flyweights = new HashMap<>();

    // Flyweight creation method
    public static Flyweight getFlyweight(String intrinsicState) {
        if (!flyweights.containsKey(intrinsicState)) {
            flyweights.put(intrinsicState, new ConcreteFlyweight(intrinsicState));
        }
        return flyweights.get(intrinsicState);
    }
}

// Flyweight interface
interface Flyweight {
    void operation(String extrinsicState);
}

// Concrete Flyweight class
class ConcreteFlyweight implements Flyweight {
    private String intrinsicState;

    public ConcreteFlyweight(String intrinsicState) {
        this.intrinsicState = intrinsicState;
    }

    @Override
    public void operation(String extrinsicState) {
        System.out.println("Intrinsic state: " + this.intrinsicState);
        System.out.println("Extrinsic state: " + extrinsicState);
    }
}

// Client class
class Client {
    public static void main(String[] args) {
        Flyweight flyweight1 = FlyweightFactory.getFlyweight("a");
        Flyweight flyweight2 = FlyweightFactory.getFlyweight("a");
        Flyweight flyweight3 = FlyweightFactory.getFlyweight("b");

        flyweight1.operation("1");
        flyweight2.operation("2");
        flyweight3.operation("3");

        flyweight1 = null; // set reference to null
        flyweight2 = null; // set reference to null

        // Garbage Collection may not happen immediately, but once it does, the shared
        // Flyweight object with intrinsic state "a" will not be deleted until flyweight3
        // is also eligible for Garbage Collection
    }
}

In this example, the Flyweight Factory is implemented as a Singleton that stores all shared Flyweight objects in a HashMap. The ‘getFlyweight‘ method first checks if a Flyweight object with the given intrinsic state already exists in the map, and if not, creates a new one and adds it to the map. This ensures that only one shared Flyweight object with a given intrinsic state exists in the program.

The ‘operation‘ method of the Concrete Flyweight class takes an extrinsic state as a parameter, but only uses it for outputting information to the console. The intrinsic state is always the same for all shared Flyweight objects with the same intrinsic state.

In the Client class, three Flyweight objects are created using the Flyweight Factory. The first two have the same intrinsic state ("a"), and so are both references to the same shared object. The third object has a different intrinsic state ("b"), so a new Flyweight object is created for it.

After the Flyweight objects are used to do some work, their references are set to null, indicating that they are no longer needed. The Garbage Collection mechanism may not immediately delete the shared Flyweight object with intrinsic state "a", since it is still being used by the third object. However, once that object is also no longer referenced by any other object in the program, the shared Flyweight object can be safely deleted.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Design Patterns interview — then scores it.
📞 Practice Design Patterns — free 15 min
📕 Buy this interview preparation book: 100 Design Patterns questions & answers — PDF + EPUB for $5

All 100 Design Patterns questions · All topics