Home   Easy-Code    Forum  Updater 
Twitter Facebook

Java Notes - Must Read

Critics Rating:

Users Rating:

1.   Profiling in NetBeans —It helps in pointing out the places(hot spots) of the problem.
2.   Two type of profiling: CPU Profiling and Memory Profiling
3.   Garbled Variable: Thread does not hold its previous values, class level variables values get changed by other threads. Local variables will be in stack and class variables will be stored in heap. Stack is also part of heap memory.
4.   Reducing number of class variables increases the performance.
5.   Synchronization is not required if notify is in shared mode.
6.   Every Object in Java has some hidden queue in it. Whenever we call wait on any object, it will be placed on the queue of that object. Every object has hidden queue to place for threads. Wait, notify, notifyAll will be called in synchronized code only to maintain queue for each object.
7.   Performance wise , Use always notify only and not notify All method
8.   Notify: notifies the thread and OS decides which thread to notify. Notify will be used when conditions of the threads are same.
9.   NotifyAll : All waiting threads will be moved to runstate. NotifyAll will be used when conditions of the threads are not same.
10.   We can call again notify if the thread condition is not satisfied instead of notify All. Having single condition for lock is design fault,this is rectified by the new implementation of Java.util.concurrent lock,allows many conditions & queues
11.   -allows many queues for each object with different conditions
12.   Priorities are platform dependant for threads.
13.   For Compound operations we need synchronization as thread may pre-empt stop in between…
14.   Use while loop to check instead of If - which makes thread to go to wait state.
15.   JIT-Compiles byte code into native code
16.   Hot Spot-profiles the code which is executed frequently& optimizes the code
1)   Default Initialization is done when constructor is called
17.   2)Then actual Initialization will be done
18.   Stores/loads back the addresses between above two steps
19.   HashMap
20.   New memory allocated & address returned then object gets fully constructed

21.   Memory Allocation is not atomic in JVM,GC code for memory allocation is not synchronized
22.   Processor/HotSpot Compiler/Cache does the instruction Reordering
23.   Synchronization forces JVM to load the data from memory and at the end of block it stores in memory
1)   synchronzation - mutual exclustion, gaurantee against cashing, gaurantee agaist re-ordering
24.   Data accessed within Synchronization block must be accessed from main memory and existing data in cache must be invalidated
25.   Data modified within Synchronization must be sent back to main memory without further delay
26.   Synchronization does not effect instructions
27.   Closing of Synchronization block/method tells JVM to update the data within main memory
28.   Memory access and memory updates are costly for Synchronization

29.   Volatile:
30.   Old JDK
31.   Always accessed from main memory
32.   An Volatile variable can get re-ordered with non- Volatile variable but cant re-ordered with another Volatile variable
33.   Doesn’t guarantee mutual exclusive

34.   New JDK
35.   An volatile variable cant get reordered with either Volatile or non-volatile variable
36.   Its got a slightly different effect as well
37.   This effect is changes made to data prior to updating the volatile variable will be synched to the memory

38.   Volatile acts as guard variable ensuring the changes made prior to updating the volatile goes to the main memory
39.   Another thread if it checks the volatile it can also see the changes made to non-volatile variable
40.   Strings:
41.   Reference array of character,length,offset
42.   Substring shares the reference of subset of characters with new object
43.   Security is the reason for string immutability
44.   Corresponding String Buffer and String Builder ,however these classes are never used in places where security is paramount important.
45.   Socket,File class never accepts parameter as string buffer but accepts parameters as strings
46.   Substring calls the constructor
47.   Call goes to object class(super class) constructor which allocates memory.
48.   Final:
49.   Old memory model:
50.   Final can be reordered and can be cached even if we set within contructor
51.   New memory model:
52.   If final field is set within constructor JVM guarentees the reference of object gets initialized (i.e., final field is set)
53.   (not only reference it will be complete state of object will be synched)
54.   If the field is a list and many objects are added then JVM will ensure entire list is synched to memory before giving reference of an object.
55.   String is immutable and this is for security – used in socket connection, files
56.   Optimistic lock – any body can view, assumes conflicts are very rare,
57.   Locks limits concurrency
58.   Locks
59.   Disadvantages of synchronization:
-   One condition per lock (object) is a design flaw
-   A Thread going for a synchronize method which is already under contention (which is already locked) cannot be pulled back and made to do something else
-   A thread doing IO cannot be pulled back. - The only way to close is the thread that is performing the IO is to close the associated stream which can be interpreted as hint to close the thread dump (prior to jdk 1.4)
-   The virtual machine locking primitives do not map well to the most efficient locking mechanisms available in hardware – no longer true from jdk 6
The above problems are solved using LOCK interface
60.   Java.util.concurrent.locks.Lock – trylock(),
61.   Lock () – similar to synchronize, finally block is must in which you have to call unlock
62.   Unlock to release the lock
63.   Condition calss – await() – causes the current thread to wait until it is signaled or interrupted. Singal(), singnalall() – similar to notify(), notifyall()
64.   Locks are implemented on top of CAS
65.   FAIR lock – in a condition, 5 threads are waiting , one thread waiting for long time, then the thread waiting for long time will get the lock, have to pay the price for fair lock
66.   ThreadLocal –allows you to declare a variable which is local to the thread but design wise you may not have forethought about it. –
67.   ThreadLocal reduces contention.
68.   Remove the connection from threadlocal map and then close the connection
69.   Ensure the threadlocal is static, only one object is available
70.   Not advisable to use vector, hashmap for synchronize
71.   One iterator doing both read/write
72.   Many iterators and threads doing only read
73.   Many iterators and threads in synchronize mode
74.   Map is internally is hashtable
75.   Hashmap – array of linkedlist
76.   Hashmap is slow – lock (pessimistic) is acquired on hashmap object
77.   Reduce the granularity of lock to the bucket
78.   Put, remove counts from modification and not get
79.   Cooperative lock – each thread should update the status of lock before accessing
80.   ConcurrentHashMap – array of array of linkedlists
81.   ConcurrentHashMap –
82.   Trick 1 - Reduce the granularity of lock to array index
83.   Trick 2 - Exploiting immutability to remove the synchronization from ‘get()’
84.   Trick 3 - using null values as an indication of indifference by another thread
85.   Final, volatile cannot get re-ordered
-   Concurrent classes are designed to work with old memory models

86.   Java.util.iteratrors – fail fast iterators comparing the mutable operations with the underlying collections and failing cleanly and quickly to avoid nullpointer exception.
87.   Java.util.Concurrentiterator- are weakly consistent iterators. Never throw concurrent modification exception but permit concurrent modifications. However, they will make the best effort to reflect the underlying connection as truthfully as possible
88.   Reduce the locks, reducing the synchronization
89.   In iterators - No object level lock, for get() no lock is there, from here the speed comes
90.   Concurrenthashmap, concurrentlinkedqueue, – does not use synchronization
91.   Issue with ConcurrentHashmap –
92.   Size, capacity, rehashing will effect the performance (is expensive operation). Since, all the hashing buckets needs to be acquired. Size, Capacity should be planned
93.   One iterators – read/write
94.   Multiple iterators – only read
95.   Multiple iterators – read/write with synchornization
96.   Profiling – performance profiling is different from normal profiling. Performance profiling normally shows hotspot under contention
97.   Processor perspective
98.   Java.util.concurrent.atomic classes implement the hardware locks (CAS)
99.   Disadvantage of CAS
-   Complexity involved in writing complex synchronization code.
-   CAS ensures atomicity of only one memory location at once.
100.   Advantage of CAS
-   Tree implemented as array
-   Non blocking Queue implement is array
-   Blocking queue implemented as linkedlist
101.   Design and implementation Technique
102.   Hashmap to be replaced with concurrenthashmap
103.   Treemap, treeset to be replaced with Concurrentskiplistmap, Concurrentskiplistset - It lets you to achieve the speed of removal and addition of a linkedlist while being very much a binary tree
104.   Treeset, arraylist – mostly doing get, and little of addition and removal then use CopyOnWriteArrayList
105.   Making object reference null should be an exception and not a norm. One such case is when the life time of the object is promoted from being local to global
106.   If you make object references null where it is not required the effect at best is code clutter and at worst is performance bottleneck.
107.   Criteria for writing finalizers
108.   Every memory allocated through the new operator – no need to clean, GC would take care of it.
-   When using native related stuff, then finalizer can be considered
109.   in case of IO related (files close) then use finalizers
110.   no native memory, no finalizer
111.   native memory and memory de-allocation is time critical and native memory is time critical, then you should provide a separate method as close() and document it
112.   if this class is meant for private usage, still no requirement for finalizer
113.   if the class is meant for public usage then finalizer acts as a safety-net, incase the user forgets to call the close (code for close and finalize are same)
114.   if writing finalize, ensure super.finalize is called. This points holds good provided the class is not meant for extending.
115.   Disadvantages of finalizer
-   a class that implements a non-trivial finalize method is handled totally differently and time of allocation itslf the jvm maintains the finalizable objects in a separate queue and parse fast allocation and de-allocation cannot be done over these objects. These objects require at-least two cycles of GC
-   While implementing finalize a programmer may reference the object spoiling the object lifecycle
-   Remember writing a finalizer without any good reason (there are non or may be a flimsy reason) is not advised. It actually slows down garbage collection tremendously.
116.   Clone
-   Fastest way to make an object.
-   Shallow copy – bit wise copy
-   Working of Cloning and construction are same till time of memory allocation, after that the construction does type specific initialization and the clone does a blind copy paste. This is the reason why clone returns x if you call x.clone()
-   Construction memory allocation is default
-   Cloning memory allocation bit wise call
-   The type of cloning object is not ensured in cloning which happens for constructor
117.   Flaws of Clone:
-   Makes a shallow copy
-   The protocol of the clone is same as constructor except it cannot be forced. The type returned by the method should be checked before using the object
-   Highly a typical use interface which means you can never check for clonability and then be sure about cloning
118.   3 choices with cloning
-   neutral to cloning
-   actively participate in cloning (iscloneable)
-   denying cloning
119.   Never call a method from constructor which is overridable
120.   Serialization
-   State of the object gets serialized not the structure
-   Classes should be available on the remote machine for the de-serialized
-   During serialization, first thing that goes into the stream is the fully qualified class name, SUID, state
-   SHA algorithm – security algorithm (also used for digital signatures)
-   If SUID is hard-coded, it means to tell the JVM it is the older version
-   If any extra field is added, the extra field would be ignored by the remote JVM during de-serialization
-   If a field is marked as transient, then those fields would be ignored during serialization
-   Serialization make a deep copy, even the references gets serialized
-   Sterilization if not implemented properly can cause stack overflow
-   If a class implements serialization, then all the private members would become public during serialization
121.   Steps of serialization

1.   extract SUID and class name from the class of the object
2.   construct an object output stream and write the above two information to the output stream
3.   check if the class of the object defines a conventional private void write object method
a.   if no, then go thru the default serialization and serialize the fields which are not transient
b.   if yes, the method is defined, class the method passing the reference of the object output stream constructed in step 2
a.   (The control is with the program) the programmer passes the control back to the serialization sub system by calling s.writeObject (default write object). At this step the serialization sub system serializes the defaultly serializable fields (not transient fields).
b.   Now the programmer serializes the fields which are transient in a custom manner
•   Reverse of serialization is de-serialization – exactly the reverse of steps will take place
-   Calling of default write/read object method even if there are no defaultly serializable fields is highly recommended. The reason is highly technical and it appends the streams with certain padding which makes the field extensive
-   If you don’t call default write/read object method and current class supports two fields adding the third fields will give exceptions.
•   While de-serialization the constructor does not get called and this process is called extra linguistic process
Advice 1 – interfaces should rarely extend serializable,
Advice 2 – classes meant for extension should rarely implement serialization

Reasons for serialization
-   For security
-   Not every object is serialized
-   If no state in the class, then no need for serialization


-   To write a class that does not force serialization and yet can participate in serialization if its sub class wants it to, the class must make its state accessible and mutable, must have an accessible default constructor. These two points are programmatic permission for participation in serialization

122.   Immutable Objects
-   performance wise immutable objects give lots of improvement

-   no set methods
-   declare variable as private and final
-   get method should return copy of mutable data not the reference
-   in the constructor – make a copy of mutable data/object not the reference
-   serialization and cloning are inconsistent with final key word, coz the compiler does not recognize the special nature of read object
-   the suid is generated on classname, implemented interfaces, extended classes, field name and types and method and implementation signatures
-   sun realizes that the extended method constructed signatures are no longer required but for backward compatibility it is required

123.   Interrupted Exception
-   if you are not the owner of thread and you get the interrupted exception and you must re assert the interrupted status so that someone up the stack who made the thread can interpret and take action on the interrupted exception. This is achieved by calling Thread.currentthread.interupt

-   instead of using for (;;) use ‘while(!thread.interrupt)’ in threads
-   Application needs to protect the boundaries which are outside the organization address.
-   When you call methods, you try and catch runtime exception (using handlers)

124.   Garbage Collection
-   GC (pause time and pause predictability) is not so important for enterprise application, but important for real time application
-   Eden generation/young generation (ss1, ss2) – objects get allocated here
-   Old generation/tenured generation
-   Permanent generation
-   Immutable objects are great for GC
-   Eden fills up – application stops and gc gets initiated
-   Stack, static, registry – figures out which are reachable, compacts them to ss1 (survivor space 1). Everything else will be garbaged
-   Objects allocation in java is 12 times faster than c++
-   Ss1 and ss2 should be smaller in the eden space

125.   Young Generation
Copying collector also known as tracing collection
-   object allocation is blindingly fast
-   affects program locality positively
-   no heap fragmentation
-   no negative virtual memory interaction (vital when tuning java)

-   copying of objects (costly operation – involve in moving the objects between ss1 and ss2)
-   the IO is negatively impacted because of change of address of the buffer by the copying collector
-   It is great for short lived objects, not so good for long lived objects
-   Tenuring time is 32 times before the object are moved to old generation/tenured
-   Can size the young generation, Tenuring time, old generation, and perm space
-   This collector collects only objects in young generation

126.   Tenure Generation/Old Generation
-   is never collected unless the young generation is collected prior to that and does not still leave enough space
-   Minor collection is for young generation, major collection is for both (full GC)
-   System.gc() triggers the major collection; programmatically there is no way to trigger the minor collection.
-   If an object in young generation has reference to old generation object, then the reachability test would be stopped for that object
-   The algorithm that is used here is mark and sweep – it is 4 phased gc, some
o   Incremental root set calculation is done here
o   Phase 1 – stop the world phase, marking phase
o   Phase 2 – concurrent phase, let the application continue, reachability test is done. Mark the objects which are reachable. Reachability phase
o   Phase 3 – stop the world phase, re-marking phase, mark the objects that are reachable
o   Phase 4 – scan the entire heap and find out which is not marked and add to free list

127.   Mark and Sweep
-   Multiphase garbage collector which allows the application to run concurrently in its longest phases
-   Do not have to pay the price of copying the objects unlike the copying collector
-   Pauses are small and you can make them predictable by appropriate options

-   Need to traverse the entire heap in the 4th phase in-order to add garbage locations to free list
-   Memory fragmentation can result but they can be minimized if the tenuring is done properly
-   Interact negatively with the virtual memory
-   Does not impact the program locality positively

-   No need to assign null values to the objects created by user that does not use native code/memory in the finalize method, if done paging in and paging out happens in the virtual memory section
-   This is a good collector for long lived objects, can be started progressively but the disadvantage is mainly fragmentation.
-   Typically used for real time and near real time applications

128.   Mark and Compact
-   Incremental root set calculation is done here
-   Phase 1 – stop the world phase, marking phase
-   Phase 2 – concurrent phase, let the application continue, reachability test is done. Mark the objects which are reachable. Reachability phase
-   Phase 3 – stop the world phase, re-marking phase, mark the objects that are reachable
-   Phase 4 – compacts the objects at the bottom of the heap

-   Affects program locality
-   No memory fragmentation
-   No negative virtual memory allocation

-   not for real time or near real time application, this is for enterprise application
-   For systems which have more than 8 cpu’s and memory than 12 to 300 GB, you have a special parallel scavaging collector which has to be used with a special option –XX:+UseAdaptiveSizePolicy. This special option means that the internal sizing of the generations are not to be handled by the program (this is called behavior based tuning)

Courtesy, Source, References & Regards: Brother2

While using this site, you agree to have read and accepted our terms of use and privacy policy.
Copyright@2009-2011 by KuGuNi.com. All Rights Reserved.