Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is java.lang.Integer.valueOf a flyweight pattern?

Why is java.lang.Integer.valueOf a flyweight pattern? I tried to find the reason but wasn't able to.

like image 683
BOSS Avatar asked Jun 29 '11 13:06

BOSS


People also ask

What is the purpose of integer valueOf ()?

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.

Why is the flyweight design pattern used?

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.

What is Flyweight pattern in Java?

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.

Where can I use flyweight design pattern?

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.


2 Answers

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).

like image 80
sshannin Avatar answered Oct 11 '22 22:10

sshannin


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.

like image 33
Mathias Schwarz Avatar answered Oct 11 '22 21:10

Mathias Schwarz