Reputation: 11549
I often write code like below.
class SomeClass {
private final Executor executor = new Executor();
void doSomething() {
executor.execute(new ExecutionListener() {
public void onEnd() {
onExecutionEnd();
}
});
}
private void onExecutionEnd() {
// Do something
}
}
The problem is every time I call executor.execute
a new instance of listener is created and all instances are doing very same thing each time. In real world, similar code is used in a mobile game and doSomething
method is called many times for many SomeClass
instances and it is not a good idea to create a new
instance each time for such case and environment. So, to avoid creating new instances, I change code to this.
class SomeClass {
private Executor executor = new Executor();
private final ExecutionListener executionListener = new ExecutionListener() {
public void onEnd() {
onExecutionEnd();
}
};
void doSomething() {
executor.execute(executionListener);
}
private void onExecutionEnd() {
// Do something
}
}
I find first code more readable but second seems more optimized. I wonder if compiler makes this kind of optimization. It can somehow detect that each listener instance will do the same thing and rather creating a new one, it may store it as a class member.
PS: I know, making SomeClass
to implement listener interface and passing this
to execute
method is an option but I do not want listener methods to be accessible from consumers of SomeClass
.
Upvotes: 1
Views: 74
Reputation: 30865
The answer is no. There is no implemented mechanism that will check statically analyse such code. Then Java compiler can not change the sense of the code. In case when you require a new instance it must provides it.
Upvotes: 2