Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java scopes inside a scope [duplicate]

Tags:

java

I've seen code like this many times where developer creates scope inside a scope.

enter image description here

There are few reasons i can think of:
1. Hiding encapsulating variables of scopes, isolating them. (which also will allow to declare variables with the same name)
2. Allowing allocated memory in scope 1 to be garbage collected when its closed.

However I dont think any of those are sufficient enought to do this...

Whats the point of doing this?

like image 496
vach Avatar asked Dec 12 '25 20:12

vach


1 Answers

As the Java Language Specification states

The scope of a declaration is the region of the program within which the entity declared by the declaration can be referred to using a simple name, provided it is visible (§6.4.1).

In other words, scope only regulates the use of names within source code. It has no effect on runtime behavior, and therefore has no effect on garbage collection.

Your first suggestion is more or less the only reason to use a block. But some times it gets too cumbersome. Personally, I've maybe used them once or twice in code I've written.


Garbage collection is partly defined by finalization of class instances. That chapter speaks about reachability

A reachable object is any object that can be accessed in any potential continuing computation from any live thread.

The JVM cannot collect such objects.

The JLS also mentions

Optimizing transformations of a program can be designed that reduce the number of objects that are reachable to be less than those which would naively be considered reachable. For example, a Java compiler or code generator may choose to set a variable or parameter that will no longer be used to null to cause the storage for such an object to be potentially reclaimable sooner.

This is also discussed in the answer to

  • Can java finalize an object when it is still in scope?
like image 151
Sotirios Delimanolis Avatar answered Dec 16 '25 21:12

Sotirios Delimanolis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!