Sie sind auf Seite 1von 8

JVM Architecture

Java Collections Hierarchy

Effective Java Notes


Item 11:Overide clone judiciously
Implement cloneable interface and override clone method If you override the clone method in nonfinal class, you should return an object obtained by invoking super.clone (clone() method should not call constructor if the class is not final) Deep copies of all the mutable fields Better alternative is copy constructor or copy factory

Item 15: Minimize mutability


Immutable Objects are simple and thread-safe (Require no synchronization).Rules to make class immutable Dont provide any methods that modify the objects state Make class as final Make all the fields as private and final

Ensure exclusive access to any mutable components (Dont share the reference of any mutable fields with the clients of the class; never initialize such fields with client provided object references. Make defensive copies in constructors, assessors, readObject methods)

Item 16: Favor composition over inheritance


Unlike method invocation, inheritance violates encapsulation (A subclass depends on the implementation details of its superclass for its proper function) If the superclasss implementation changes, the subclass may break, If the superclass acquires a new method in a subsequent release and you have the bad luck to have given the subclass a method with the same signature and a different return type, your subclass will no longer compile Inheritance propagates any flaws in the superclasss API, while composition lets you design a new API that hides these flaws To avoid this fragility, use composition and forwarding instead of inheritance

Item 17: Design and document for inheritance or else prohibit it


Designing a class for inheritance places substantial limitations on the class Inherit a class only of if there is a genuine subtype relationship and the class is designed to be subclasses the class must document its self-use of overridable methods (non-final and either public or protected) To document a class so that it can be safely sub classed, you must describe implementation details that should otherwise be left unspecified. The only way to test a class designed for inheritance is to write subclasses Constructors must not invoke overridable methods Not a good idea for a class designed for inheritance to implement Cloneable and Serializable interfaces, as they place a substantial burden on programmers who extend the class. If implemented neither clone nor readObject may invoke an overridable method, directly or indirectly

Item 22 Favor static member classes over nonstatic


4 different kinds of nested class - static member classes, nonstatic member classes, anonymous classes and local classes nonstatic -> If each instance of the member classes needs a reference to its enclosing instance static -> Otherwise anonymous classes -> Need to create instances from only one location and there is a preexisting type that characterizes the class Local Class -> Other wise

Java Memory Management


Types of Java References Strong References : Normal reference Soft Reference : When you want the referenced object to stay alive until the host process is running low on memory. GCed any time after there are no strong references to the referent, but is typically retained until memory is low Weak Reference : When you don't want to influence the referenced object's lifetime; you merely want to make a separate assertion about the referenced object, so long as it remains alive. GCed any time after there are no strong or soft references to the referent Phantom Reference : GCed any time after there are no strong, soft or weak references to the referent ,typically used in conjunction with a ReferenceQueue to manage cleanup of native resources associated with the object without using finalize methods (more on this later)

GC Metrics Throughput : percentage of the total run time not spent performing GC Pause Time: Time taken when the application code stops running while GC is performed, interested in the number of pauses, their average duration and their maximum duration Footprint : current heap size (amount of memory) being used Promptness : how quickly memory from objects no longer needed is freed

GC Monitoring -verbose:gc outputs a line of basic information about each collection -XX:+PrintGCTimeStamps outputs a timestamp at the beginning of each line -XX:+PrintGCDetails implies -verbose:gc & outputs additional information about each collection -Xloggc:gc.log implies -verbose:gcand -XX:+PrintGCTimeStamps & directs GC output to a file instead of stdout

Generation Garbage Collection Process


Generational GC assumes that The most recently created objects are the ones that are most likely to become unreachable soon for example, objects created in a method and only referenced by local variables that go out of scope when the method exits The longer an object remains reachable, the less likely it is to be eligible for GC soon (or ever)

Heap Structure

All of the GC algorithms used by Java are variations on the concept of generational GC 1. First, any new objects are allocated to the eden space. Both survivor spaces start out empty. 2. When the eden space fills up, a minor garbage collection is triggered. Referenced objects are moved to the first survivor space. Unreferenced objects are deleted when the eden space is cleared. 3. At the next minor GC, the same thing happens for the eden space. Unreferenced objects are deleted and referenced objects are moved to a survivor space. However, in this case, they are moved to the second survivor space (S1). In addition, objects from the last minor GC on the first survivor space (S0) have their age incremented and get moved to S1. Once all surviving objects have been moved to S1, both S0 and eden are cleared. Notice we now have differently aged object in the survivor space. 4. At the next minor GC, the same process repeats. However this time the survivor spaces switch. Referenced objects are moved to S0. Surviving objects are aged. Eden and S1 are cleared. 5. After a minor GC, when aged objects reach a certain age threshold they are promoted from young generation to old generation. 6. As minor GCs continue to occure objects will continue to be promoted to the old generation space. 7. Eventually, a major GC will be performed on the old generation which cleans up and compacts that space.

Ergonomics : Sun refers to the automatic selection of default options for GC based on hardware and
OS characteristics as "ergonomics" The goal of ergonomics is to provide good performance with little or no tuning of command line options by selecting the garbage collector, heap size, and runtime compiler at JVM runtime, instead of using fixed defaults

Most applications Serial Collector will be adequate enough An example of a situation where the serial collector is not expected to be the best choice is a large application that is heavily threaded and run on hardware with a large amount of memory and a large number of processors.

Performance considerations 2 primary measures Throughput and Pause times Different applications have different performance requirements. May be for a webserver throughput is more important and pauses may be tolerable or simply obscured from network latencies. For an interactive graphic program even short pauses may negatively affect the user experience A particular generation sizing chooses a trade-off between these considerations. For example, a very large young generation may maximize throughput, but does so at the expense of footprint, promptness and pause times. young generation pauses can be minimized by using a small young generation at the expense of throughput. The best choice is determined by the way the application uses memory as well as user requirements. Thus the virtual machine's choice of a garbage collector is not always optimal and may be overridden with command line options

GC Algorithms
Serial: -XX:+UseSerialGC uses the same thread as the application for minor and major collections Throughput: -XX:+UseParallelGC uses multiple threads for minor, but not major, collections to reduce pause times good when multiple processors are available, the app. will have a large number of short-lived objects,and there isnt a pause time constraint Concurrent Low Pause: -XX:+UseConcMarkSweepGC only works well when objects are created by multiple threads? uses multiple threads for minor and major collections to reduce pause times good when multiple processors are available,the app. will have a large number of long-lived objects, and there is a pause time constraint

GC tuning
Throughput goal -XX:GCTimeRatio=n What percentage of the total run time should be spent doing application work as opposed to performing GC? Maximum pause time goal -XX:MaxGCPauseMillis=n What is the maximum number of milliseconds that the application should pause for a single GC? -XX:MinHeapFreeRatio=n, -XX:MaxHeapFreeRatio=n o bounds on ratio of unused/free space to space occupied by live objects heap space grows and shrinks after each GC to maintain this,limited by the maximum heap size

-XX:NewSize=n, -XX:MaxNewSize=n default and max young size (eden + survivor 1 + survivor 2) -XX:NewRatio=n ratio between young size and tenured size -XX:SurvivorRatio=n ratio between the size of each survivor space and eden -XX:MaxPermSize=n upper bound on perm size -XX:TargetSurvivorRatio=n target percentage of survivor space used after each GC XX:+DisableExplicitGC when on, calls to System.gc() do not result in a GC (off by default) XX:+ScavengeBeforeFullGC when on, perform a minor collection before each major collection (on by default) XX:+UseGCOverheadLimit when on, if 98% or more of the total time is spent performing GC,an OutOfMemoryError is thrown (on by default) Selecting a GC Collector Serial : If the application has a small data set(<100MB)/runs on single processor/no pause time requirements Parrallel(Throughput) : peak application performance is the first priority and (b) there are no pause time requirements or pauses of one second or longer are acceptable, Concurrent : If response time is more important than overall throughput and garbage collection pauses must be kept shorter than approximately one second If the recommended collector does not achieve the desired performance, first attempt to adjust the heap and generation sizes to meet the desired goals. If still unsuccessful, then try a different collector: use the concurrent collector to reduce pause times and use the parallel collector to increase overall throughput on multiprocessor hardware.

Generational Sizing The bigger the young generation, the less often minor collections occur. However, for a bounded heap size a larger young generation implies a smaller tenured generation, which will increase the frequency of major collections. If survivor spaces are too small, copying collection overflows directly into the tenured generation. If survivor spaces are too large, they will be uselessly empty. ---End Java Memory Management-----

Java local variable visibility in anonymous inner classes - why is 'final' keyword required?
Local classes can most definitely reference instance variables. The reason they cannot reference non final local variables is because the local class instance can remain in memory after the method returns. When the method returns the local variables go out of scope, so a copy of them is needed. If the variables werent final then the copy of the variable in the method could change, while the copy in the local class didnt, so theyd be out of synch. Ex: if you could use non-final local variables in an anonymous class then which button should it enable in the following code segment.
Button btnDownload = new Button(myparent, SWT.NONE); btnDownload.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { btnDownload.setEnabled(false); // I CAN'T } }); btnDownload = new Button(somethingelse , SWT.NONE); btnDownload = null ;

Why String is immutable


String has been widely used as parameter for many Java classes e.g. for opening network connection, you can pass hostname and port number as string , you can pass database URL as string for opening database connection, you can open any file in Java by passing name of file as argument to File I/O classes. if String is not immutable, this would lead serious security threat Most important reason that String is immutable is that it is used by the class loading mechanism, and thus has profound and fundamental security aspects. Had String been mutable, a request to load "java.io.Writer" could have been changed to load "mil.vogoon.DiskErasingWriter" JVM maintians String pool for literl strings for performance reason.If string was immutable string pool would have been impossible as one change could affect all the references in the pool Since String is immutable it can safely shared between many threads

Imp Links 24 Collections Framework Interview Questions & Answers for Java developers http://www.fromdev.com/2008/05/java-collections-questions.html

Das könnte Ihnen auch gefallen