Why is java.lang.Integer.valueOf a flyweight pattern? I tried to find the reason but wasn't able to.
valueOf(int a) is an inbuilt method which is used to return an Integer instance representing the specified int value a. Parameters : The method accepts a single parameter a of integer type representing the parameter whose Integer instance is to be returned.
Flyweight pattern is primarily used to reduce the number of objects created and to decrease memory footprint and increase performance. This type of design pattern comes under structural pattern as this pattern provides ways to decrease object count thus improving the object structure of application.
Flyweight is a structural design pattern that allows programs to support vast quantities of objects by keeping their memory consumption low. The pattern achieves it by sharing parts of object state between multiple objects. In other words, the Flyweight saves RAM by caching the same data used by different objects.
Flyweight pattern is used when we need to create a large number of similar objects (say 105). One important feature of flyweight objects is that they are immutable. This means that they cannot be modified once they have been constructed.
If we look at the source for valueOf
, we can get a hint:
Source of java.lang.Integer lines 638-643:
public static Integer valueOf(int i) {
assert IntegerCache.high >= 127;
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
It looks like the Integer class maintains a cache of Integer objects for common values. Rather than make a new one every time somebody asks for valueOf
, it just returns a reference to one that already exists. Therefore, if you call Integer.valueOf(1)
multiple times, you'll end up getting the same object back every time (not just equivalent objects).
This sounds like you have been asked to solve an exercise.
If you call the method twice with the same argument, it may return the same object thereby limiting the memory usage. This fits the definition of flyweight pattern.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With