Using Statics: Various Notes


  • Avoid turning an instance method into a class method for the sole sake of making it static. Ensure that either it semantically makes sense or at least one additional class needs access to the class method before doing so.

    Garbage Collection

    Java tries its best to manage your application's use of memory as it executes. Memory is a precious, limited commodity in most computer systems. Every time your code creates an object, Java must find memory space in which to store the object. If Java did nothing to manage memory, objects put in memory would stay there forever, and you would very quickly use up all available memory.

    Java uses a technique known as garbage collection to manage your application's memory use. The Java VM tracks your use of all objects; from time to time it runs something known as a garbage collector in the background. The garbage collector reclaims objects that it knows you no longer need.

    You no longer need an object when no other objects refer to that object. Suppose you create an object within a method and assign it to a local variable (but not to anything else). When the VM completes execution of the method, the object remains in memory, but nothing points to itthe local variable reference is only valid for the scope of the method. At this point, the object is eligible for garbage collection and should disappear the next time the garbage collector runs (if everyou can never guarantee that the garbage collector will run).

    If an instance variable refers to an object, you can give the object up for potential garbage collection by setting the value of the instance variable to null. Or you can wait until the object containing the instance variable is no longer referred to. Once nothing refers to an object, any objects it in turn refers to are also eligible for garbage collection.

    If you store an object in a standard collection, such as an ArrayList, the collection holds a reference to the object. The object cannot be garbage collected as long the collection contains it.


  • Static-side collections (for example, storing an ArrayList object in a class variable) are usually a bad idea. A collection holds a reference to any object added to it. Any object added to a class collection stays there until it is either removed from the collection or until the application terminates. An instance-side collection doesn't have this problem; see the sidebar for a brief overview of how garbage collection works.



Agile Java. Crafting Code with Test-Driven Development
Agile Javaв„ў: Crafting Code with Test-Driven Development
ISBN: 0131482394
EAN: 2147483647
Year: 2003
Pages: 391
Authors: Jeff Langr

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net