Friday, 1 April 2016

OCAJP Test Notes


Data types:

Java has two kind of var. types, i.e. primitive and reference type.
Reference variable is used to store a reference, which points to an instance.
Primitive type: byte(8), char(16), short(16bit), int(32), long(64), and floating float(32), double(64), etc
Java use four type integers  byte, short, int, and long; and two type of floating-point numbers: float(single precision) and double(double precision). Normally you should use the double type, because it is more accurate than the float type. 

suffix: float(F) double(D); and long(L)
octal(0) and hex(0xFFFF) literals: 

Type casting is required when assigning a value to a variable of a smaller type range, for instance,
double d = 4.5; 

int i = (int i)d

Primitive Wrapper Classes
Each primitive has its reference type, i.e. a wrapper class extended from Number.

Integer a = 1;
Float b = 1.0f;

Can you compare them in a conditional statement?
No. for they have different class type.

Can you use method compareTo() to compare each other?
No. for in the compareTo() method requires the same type of object.
The same principle as applying if(a==b){}; resulting a compilation error, "incompatible types."

However, for the primitive types
int a = 1;
float b = 1.0f;
You may use conditional statement to compare different data types .

Java narrowing primitive convention: applied on the char, byte and short, required to be cast in method invocation. 
What happens with the following code?
Short s = new Short(9); 
You get a compiling error here. "no suitable constructor", because 9 is considered as a int type.
So, casting 
Short s = new Short((short)9); 
reference(class): String, Enum, and arrays 

Variable Declaring:
In java chained declaring is not allowed.  int a = b = c=100 causes a compiling error, for the variable b and c is considered not declared yet.  How about this? int a, b, c=100; 

Identifier Naming
starting "_" or "$" or any letter; it cannot start with a digit. it cannot be a reserved word; an identifier can be of any length. 
$$ is a valid identifier. 
int $$ = 0;

Flow Control
Basically, 
if ... else
if() ... else if() ... else if() ... else

Switch 


A switch works with the byte, short, char, and int primitive data types; enum. types; and now String class type. and a few primitive wrapper classes Character, Byte, Short, and Integer.


Note: switch cannot work with long, float and double. Ensure that expression in any switch statement is not null to prevent a NullPointerException from being thrown.

Loop: for, while, do-while;
while(Boolean condition){ }
do{...}while(Boolean condition)
for(int i;i...}


specific case://infinite loop
for(;;){
}

for(Element e: vector){
...}

break or continue in a loop (labeled or unlabeled )

break without label: quit from entire loop block.
break with label: break from the labeled statement block, which contains a loop or loops.

continue without label: quite from the current iteration, and continue to the next loop.

  
return
the last of branching statement is the return. 1) return values defined in the method signature; 2) return without any value, meaning that quit from current method, backing to the method invoking  point.



Class and Method


Member variables

variables maybe defined by the primitive types, for instance: int, float, double, char, byte , short etc

or by the reference types: String, array(float x[]), or created from classes



variable modifiers: public or private, static final etc.

public: accessible by all classes.

private: only within the class



member variables in the class: fields

variables declared in the block of code or methods; local variables

variables declared in the method argument: parameters(local variables)


member variable modifiers(4 types): public, protected, private and without modifier;
method naming convention
verb(lower case) + (adj. / noun)



Constructor

You many provide no constructor; but compiler may provide a default one (non argument), in which a non-argument constructor will be called from the super class. So you might need to take care of here. If the super class doesn't offer an explicit non-argument constructor, then achieving a compiling error. 

Note: If a constructor does not explicitly invoke a super-class constructor, the Java compiler automatically inserts a call to the no-argument constructor, super(), of the super-class. If the super class does not have a no-argument constructor, you will get a compile-time error. Object does have such a constructor, so if Object is the only super-class, there is no problem.

Please note: ref. to super class constructor, super() must be put in the first line of the sub-class constructor. 



class modifier: public(accessible by all classes in all packages); or without any modifier(implicitly,  accessible by the classes in its package.)



GC Principle.

<10 i="" p="">When an instance(object) has not been referred any more; it could be drop out the memory. 
<10 i="" p="">GC automatically and periodically checking such a object, and release the resource occupied by it. 
it could be forced to be released, by setting to be null. it doesn't mean you can force GC to do clearing, but just informing it; he can remove it.

List list = new ArrayList();

VM create an instance ArrayList in the heap memory and gives back the reference value in the list variable; 

When the instance has no need any more, then we may set list = null, and inform the GC to recycle this part of resource.  


Using this keyword.

1) this is used to ref. to current class instance itself. the purpose is to avoid the shadow of the variable by the method input parameters.  public void setAge(int age){this.myAge = age;};

2) this used in the constructor, to refer to other constructors.

this(x,y); invoking used to invoking other class constructor. If present, the invocation of another constructor must be the first line in the constructor. public Human(int age){ this(age,0.0) };


Access control to Class members(fields) 

Public: can be accessed from current class, current package, and classed located at external packages; so it could be accessed in anywhere of the application. 
Protected: can be accessed from current class, current package, but only the sub-classes located at the other packages
no modifier(default): it does't mean it is the same to private declaring; not at all. on this case, field could be accessed by the classes in the current package; and it is hidden from the sub-classes. 
Private: can be  only accessed from current class, not even to the sub-classes. fields are truly hidden/encapsulated. 

Please note here, class method (static method) cannot access instance method and instance var. 
However, instance method can directly access both. The purpose of class fields and methods are for sharing common attributes and behaviors. How about another way round?thus why a class method really interested at a specific instance attribute or method? so this was prohibited .

Class method and class var. keyword (static); there is no need to instantiate instances to access such a var or a method. 

Using "import static package" can even over-skip the class qualifications.  

Class constants naming:  static final, followed by naming; it must be capitals. If more than one word, please using '_' to make them concatenated.  


Initialize Class fields

The most simple way to init. them at the start of class. that is what we often do. in the principle, you can init. them in any part the class. certainly we don't do like that.


1) using static block code: static { init. code here } to init. class fields
A static block will be first invoked as the class is loaded by JVM, no matter where it has been put in the class.  so no matter what, it will be implemented before the constructor. it could has several static block, and they will be implemented automatically according to their occurrence sequence.   

2) private static final method: well you have to use a static method to access static fields. 

Initialize Instance fields
Certainly we sometime to init. instance fields in the constructor, i.e. declaring instance var at the start of the class, and init. them in the constructors. 

sharing common init. code in several constructor? 1) using init. block; Java compiler will copy the block of init. code into each of the constructor. 2) using private final method to re-use the init. code.  I think this is a better strategy. 

private final void init(){ }

Inner Class

I feel it is really not that often to use inner class. is there a private class? normally, we define classes that we want to use these templates to cast new instances; So in the real life, what is a private class? actually, it is a Inner class.

Class A{   Class B{} }

Interface
Interface is an protocol defined how a group of classes communicate with external ones. interface could be modified as public or no modifier; as having no modifier it is considered as  an interface used only in the current package.

Interface contains two parts: constants and abstracted methods. in java 8, it is allowed to declare implemented method, but it must be static.

Interface variables and methods, may omit modifier; by default they will be understood as public abstracted methods and "public static final " respectively.
public interface myinterface{ double PI = 3.14; void setRidus(double r); double getRidus(); }

When an interface need adding new abstract methods; it is best to extend from it, thus it won't break existing code. so an interface could extends from many other interfaces. please, an interface cannot implement other interfaces; it doesn't make any sense, for interface cannot instantiate those inherited abstract methods. 


Interface gives a chance of  carrying out multiple inheritances in Java. It describes that its sub-class is a type like the Interface.  So two classes implementing the same interface, could be considered as having a similar type. I use the wording, "something like" relationship, for I don't think it is exactly same as the consequence due to "extends".  

Inheritance
Inheritance describes a IS-A relationship between two objects. For instance, an Apple is a Fruit, thus Fruit could be designed as a super-class, and Apple as its sub-class. The common attributes and behaviors among fruit could be inherited by Apple class.  

Sub-classes can inherit fields and methods from the interface, abstract class or normal class. 
The instance method could be overridden in sub-class and class fields and method could be hidden in the subclass due to shadowing.

Instance method: can be overridden in sub-class.
Explicitly using @override to instructs comelier.
Overriding convention: the method must have the same signature, parameters(including numbers) and return type. A overriding method can also return a sub-type of the super class, This is also called co-variant return type. However, for the primitive return types, they must be the same. 

Class method: cannot be overridden by instance methods in a sub-class; however it can be hidden by a static(class) method in the sub-class, if sub-class declare the same signature as the the class method in the super-class. 

Please note: a sub-class instance method cannot override a static class-method in the super-class(private method is an exception, for it cannot be inherited); only static method in the sub-class hides another static method in the super class. Otherwise you will get a compiling error.

The same principle: a sub-class static method cannot override a super-class instance method; otherwise you will get a compiler error.

Method Overriding:

Methods having the same signatures, the same argument, but could be distinguished by the return types. Return the same primitive type OR Return a class or Interface type, following a co-variant return type. In addition, access modifier should be the same.

Overriding distinguished by 1) the inheritance, and then must be instance  methods. 2) then the same signature and argument(type, sequence and number)  3) return type must be same for the primitive; for the reference type it must  be the sub-types. 4) access-modifier must be the same as the super-class.

Overriding is only relevant to the instance methods. Instance fields cannot be overridden, but only hidden due to shadowing. The same principle for the class methods and fields, they are not able to be overridden.

Method cannot be overridden:
Private method cannot be inherited, so it cannot be overridden. For the sub-class, it is a new method.
Final method in the super-class cannot be overridden, just like final class cannot be extended.
Static method cannot be overridden, but could be hidden in the sub-class.

Please note: hidden fields/static methods are rarely used.

Virtual Method Invocation:

This principle is only relevant to the overridden instance methods. For hidden class methods, they can be directly referred by real class name; however, for overridden methods are referred is determined by the actual class used to instantiate the reference variable. Meaning that, variable type could be declared as a super-class, but in the run-time it could be instantiated as any sub-class object. So invoking overridden instance methods, requires to watch out the object class type. 

JVM calls the appropriate method for the object that is referred to in each variable. It does not call the method that is defined by the variable's type. This behavior is referred to as virtual method invocation and demonstrates an aspect of the important polymorphism features in the Java language.

Super keyword:
For overridden instance methods, the overridden super-class instance methods can be accessed by the super keyword. 

Method overloading:
methods they have same method signatures, but different input parameter types or numbers of parameters. 

Overloaded methods are differentiated by the number and the type of the arguments passed into the method. the return type differences have no matters with determining overloading or not.  

Note: In a subclass, you can overload the methods inherited from the super-class. Such overloaded methods neither hide nor override the super-class methods—they are new methods, unique to the subclass.


Note: Overloaded methods should be used sparingly, as they can make code much less readable.

Why static method cannot be overridden?
Static methods cannot be overridden because method overriding only occurs in the context of dynamic (i.e. run-time) lookup of methods. Static methods (by their name) are looked up statically (i.e. at compile-time).


Actually, you might have noticed that as using a static method, you may directly qualify it by using the class name; this won't confuse compiler at compiling time; it exactly know which method should be referred. however, for the instance method, then it has a dynamic selection issue as in a run time.  

Overriding vs Overloading
in sub-class you may overload an inherited method from the super-class. This is not hiding or overriding; but just a new instance method.

Overriding is a concept associated with the inheritance; which gives sub-class freedom to redefine the behavior locally but keeping consistency with the super-class on the common behaviors.

Overloading follows a similar idea keeping the same method signatures, but it varies on the input arguments's numbers, and their types. the return type doesn't really a matter to distinguish. 

Polymorphism
for instance, a woman may have different roles, as a mother, sister, daughter, or an aunt.  So on the scenarios she may have different behaviors.

Inheritance and overriding offers Polymorphism.
The Java virtual machine (JVM) calls an appropriate method for the object that is referred to in each variable. It does not call the method that is defined by the variable's type. This behavior is referred to as virtual method invocation and demonstrates an aspect of the important polymorphism features in the Java language.

Final a method and a Class
Declaring some or all of a class's methods final, to indicate that the method cannot be overridden by sub-classes; Declaring an entire class final — this prevents the class from having sub-classes. This is particularly useful, for example, when creating an immutable class like the String class.




Object Class

java.lang.object is the root for the all java class. it offers several useful methods.

  • protected Object clone() throws CloneNotSupportedException
          Creates and returns a copy of this object. object must implements clonable interface. 
  • public boolean equals(Object obj)
          Indicates whether some other object is "equal to" this one. You have to note this equals only use "==", so it may not fit what your need, so you may override it. 
  • protected void finalize() throws Throwable
          Called by the garbage collector on an object when garbage
          collection determines that there are no more references to the object. 
  • public final Class getClass()
          Returns the runtime class of an object.
  • public int hashCode()
          Returns a hash code value for the object.
  • public String toString()
          Returns a string representation of the object.

The hashCode() Method

The value returned by hashCode() is the object's hash code, which is the object's memory address in hexadecimal. By definition, if two objects are equal, their hash code must also be equal. If you override the equals() method, you change the way two objects are equated and Object's implementation of hashCode() is no longer valid. Therefore, if you override the equals() method, you must also override the hashCode() method as well.


Abstract Class

Abstract class is a common place for a group of classes to put their common attributes and methods; and declaring common abstracted behaviors.

When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, the subclass must also be declared abstract.

Unlike interfaces, abstract classes can contain fields that are not static and final, and they can contain implemented methods.

Abstract class may implement interfaces; however unlike concrete classes, an abstract class has no need to implement all of abstracted method defined in the interfaces.  it may even don't implement any abstracted method defined in the interface. 


I think this is not hard to understand. Abstract class is abstract like an interface; the most important is all of its sub-classes have to implement its interface methods. 


Abstract Class vs Interface
abstract class define or say abstract common features and behaviors of classes, and in one place. that is why it may contains implementation of the methods, while leaving sub-classes the freedom to implement locally abstracted methods.


So Abstract class may contain instance or class variables and instance and/or class methods.
The interface, only contains class variable; and public methods.


 Exception:

Checked exception means you need to check it.
Unchecked exception means you don't need to check it.

All java exceptions and errors are Throwables. 

Checked exception is extended from "Run-time-Exception"
Unchecked exception is extended from "Exception"

If checked exception is not caught, then you need to 'throws' it.

When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the run-time system is called throwing an exception.


Generics:
Java generics is introduced from Java 5. The basic purpose behind using generics is to enable you to mark your intent of using a class, method, or interface with a particular data type. Generics add compile-time safety to collections. By this way, a type inconsistency may be found in a early time, rather than in the run time. Generics can be applied on a class, an interface, a method, and even a constructor. They are called generic classes, generic methods, or generic constructors.

The key for Generics is to declare formal type parameters  at a class or method level. Type parameter follows a naming convention: using <Single Capital Letter>. A formal type parameter can be replaced by actual data type in the compiling time, but erased in the runtime.

For a generic class, formal generic types should be declared after class name;
For a generic method,  formal generic type should be declared after access modifier before the return type. This is important, otherwise compiler may don't know what's return type.

Actual type can be inferred by the compiler .
for class generics : type parameter inferred from the type argument.
for method generics: type parameter inferred from the real data type.

The type variable can be presented by a wildcard(?); it means it could be any types. Wildcard can be extended from a upper bound type(extends) or a super type of a lower bound type(super). 


Collection:
A collection is a container, storing a group of  elements(objects).
Java collection framework support three types of collections: Set, List, Queue and Map.
Set: HashSet, LinkedHashSet and TreeSet
List: ArrayList, LinkedList
Queue: ArrayDeque

Map: HashMap, LinkedHashMap, and TreeMap

Linked: keep insertion order, not sorted
Hash:  keep no insertion order, not sorted
Tree: keep no insertion order, sorted. 
Set: unique, element must be comparable. 
Map: keep key value pairs. 


How elements in the are sorted? here you may hard code. 
1) using default, element.compareTo(another element) method;  the class need implements java util Comparable interface.
2) using costumer defined external Comparator, which implements implements java util Comparator java.io.Serializable, 

public interface Comparator{
public int compare(Object element1, Object element2);
public boolean equals(Objects element);}


Map: (key, value) one to one relationship.
HashMap : not synchronized.  null key and null value
HashTable: synchronized.  not allowed null key and null value.



Can you put more than one class in one java file?
Yes. the only limitation is you only can have one public class. the rest must be default access.

Super-class has explicitly declare a constructor with arguments, then JVM will automatically provide no non-argument for it. So you need to watch out here, as define a non-argument in the sub-class extended from it. It will cause a compiling error, for the super-class has no a non-argument constructor defined yet.

Is able to declare public static void main(String args[]) in other access modifier?
no, you must declare main class as public.  you cannot use protected, default modifier, and private.

final public static void main(String args[])
final means here for the static method cannot be shadowed.
final means for the instance method, it means the method cannot be overridden.

java constant declaring: must be final static int xxx = yyy; the constant must be initialized as  declaring, otherwise it will give a compiling error. so what is a constant is? it should be a value that commonly shared by the instances, and it cannot shadowed.

All java arrays are objects, int[] array={1,2,3}; array instanceof Object = true. 

If you have a Object object = null; what happens as System.out.println(obejct)?
It will print out 'null'; It won't cause null pointer exception, for there is no operations on the null.


What happens when you print out b.i?
class A{
private int i = 10;
public void f(){}
public void g(){}
}
class B extends A{
public int i = 20;
public void g(){}
}
public class C{
A a = new A();//1
A b = new B();//2
}

No you cannot. for b has been declared as Type A, for the A the i is a private field, not accessible.

static method cannot access instance fields, but only static fields.
instance method can access class field and instance field both.

Keyword final

It can be used to modify class, variable, and method. I think it try to define something it is final; not allowed to be changed.

a final class cannot be extended; a final variable cannot be hidden(??? i didn't see this.), anyway it will be constant; it cannot be assigned a new value; a final field must be initiated as declaring it; a final method cannot be overridden.

final modifier cannot be applied on the constructor, for constructor cannot be inherited.



char, byte, short int are int type, but you need to watch out type narrowing, meaning that when assigning a int number to byte, char, short; requiring casting.


Keywork transient
transient keyword, telling JVM the modified variable is not serialize-able/persisted.


Sunday, 13 March 2016

Interface vs abstract class

It may be confusing at the start. I think it should be explicit as term's literal meaning.

Interface is a communication protocol defines how a class of instances interacts with the external world, i.e. other instances. So interface method is about abstract instance methods.

Abstract class is a place to put common attributes and methods of a class in one place. It could be class or instance members.

Interface and abstract class are abstract, so they won't have any implementation. One class can implement several interfaces, depending on how many deceives or channels via which it interacts with the external objects. Abstract class could have implemented method and fields. They are common members of the class or its instances.

Interface can only define constants, and fields defined in the interface are implicitly considered as 'public static final'. Interface abstracted methods can only be defines as public, for they are used as communication to the external.

Abstract class as explained before, as explained it is a common place to put all the common features in one place; so you may define member access, as public, protected, default, and even private.

We can define constant and abstracted method in the interface; in the java 8, we may declare static method also in the interface.




What is Servlet


Servlet sounds like "let/making server do something". Actually, it bind the java class and HTTP request together. Meaning that, it is a common interface and handler, which is able to handle remote request and dispatching to the underlying java class handler, and generate response to the remote caller.

Servlet life cycle, init(), service(), and destroy().  they are implemented by the container.
init() the input parameters extracted from httprequest; service() is the functional handler; when the requested task has been done, then container will call destroy() to terminate servlet.

Wednesday, 16 June 2010

About Java Run Out Perm. Space

Recently, I met a issue on "run out memory of perm. space." in Tomcat server.

What is the memory leak? The dynamically allocated memory has become unreachable.

1) C/C++ is prone to cause memory leak, because it has no auto garbage collection mechanism.
2) JAVA: unbounded memory use, but

There are two types of Memory in JVM: Heap and Permanent.
What Heap for? dynamatically generating instances.
What Permanent for? store the templates, i.e. Classes, but not dynamically used.

So run out the memory of this part, mostly because it has been used out of boundary of the space, at least I think so. So increasing permananent memory from the default of 64mb to 150 mb.

Add java option: -XX:MaxPermSize=150m

Stack memory: 
In addition: java vm also manage a stack for the handling local var. and function calls; each thread has its own stack, seen as a private memory. If there is no memory left for storing local var., then java will throw a stack overflow error.

Heap memory: 
Java  VM maintain a memory space for a common usage for all threads, where all objects are created there. no matter where these class having been instantiated. When heap runs out, then java throws  java.lang.OutOfMemoryError.

So there are 3 different kind of memory usage in java. heap perm. and stack.


Monday, 21 September 2009

HttpURLConnection: java.net.ConnectException: Connection timed out

CodeGuru Forums > Java Programming > Java Programming > HttpURLConnection: java.net.ConnectException: Connection timed out:


PDA

Click to See Complete Forum and Search --> : HttpURLConnection: java.net.ConnectException: Connection timed out:


vadirajak1

January 11th, 2005, 03:44 AM

Hi,
I am trying to read from a URL and display the contents in an Applet. I am using URL,HttpURLConnection classes. I am consistently getting Connection time out Exception. I am unable to connect. Could any one help me out with this. I have tried some TimeOut handler classes available on the net but still I am getting the same Exception. Please provide your comments if you have come across similar problems before.
Here is the code Iam using
url = new URL((URL)null, str, new HttpTimeoutHandler(15000)); // timeout value in milliseconds
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.connect();
nputStream is = httpConnection.getInputStream();
Thanks & Regards,
Vadi


cma

January 11th, 2005, 07:57 AM

Can you connect to the server directly, say, using your browser?


cjard

January 11th, 2005, 08:53 AM

connection timeouts occur when:
the IP address for the requested server is successfully found
connection establishment packets are dispatched to the IP address
the destination address deliberately ignores or does not receive them
similar to connection timeout is Connection Refused, but in this case the destination system is actually sending packets back saying "go away, there is no service running on the port you are trying to connect to"
your packets are just being lost.. either the system or some intermediate system is firewalled. follow CMA's advice.. if you cant connect using telnet, a browser or some other app, its a network problem, not a java one


vadirajak1

January 12th, 2005, 01:11 AM

I am able to connect to the url through browser and able to see the data that is there. But when trying to connect through the code, I am getting the connection time out exception. So this must not be a Network/Firewall related issue. Also, the same code is working fine when we tried testing it from the US, but it is giving the timeout Exception when tried from India. Is this a simple time out issue? If so, even some of the time out handlers available on the net are not solving the issue? Can anyone suggest a way out please.
Thanks & Regards,
Vadi


cjard

January 12th, 2005, 07:52 AM

check your browser proxy settings
try using telnet to connect to the same server that youre using in code and the browser:
telnet www.google.com 80


codeguru.com
Copyright 2009 WebMediaBrands Inc., All Rights Reserved.

Friday, 4 September 2009

Java Memory Insufficent

 

The JVM heap space is where all Java objects are stored, as well as memory used by the garbage collector. Sun recommends increasing this value for server applications,

Large server applications often experience two problems with these 
defaults. One is slow startup, because the initial heap is small and
must be resized over many major collections. A more pressing problem
is that the default maximum heap size is unreasonably small for most
server applications.



If an application gobbles up memory until it throws an OutOfMemory exception, or seems to be spending an excessive amount of time doing garbage collection, a heap dump can help track down the source of the problem.



Three type of Insufficent Memory:



1. Heap memory error: when an application creates a new object but the heap does not have sufficient space and cannot be expanded further, and OutOfMemoryError will be thrown with the following error message:



java.lang.OutofMemoryError: Java heap space



2. Non-heap memory error: The permanent generation is a non-heap memory area in the HotSpot VM implementation that stores per-class structure as well as interned strings. When the permanent generation is full, the application will fail to load a class or to allocate an interned string, and an OutOfMemoryError will be thrown with the following error message:



java.lang.OutOfMemoryError: PermGen space



3. Native memory error: The Java Native Interface(JNI) code or the native library of an applicaiton and the JVM implementation allocate memory from the native heap. An OutOfMemoryError will be thrown when an allocation in the native heap fails. For instance, the following error message indicates insufficient swap space, which could be caused by a configuration issue in the operating system or by another process in the system that is consuming much of memory.



java.lang.OutOfMemoryError: request <size> bytes for <reason>. Out of swap space?



Reasons for Insufficent Memory



Momory Leaks: An applicatoin keeps a reference to an object that it no longer needs. Garbage collector cannot free this part of memory.



Finalizers: excessive use of finalizers.



DeadLocks:



Looping Threads:



High Lock Contention:



 











          How to remotely monitoring JVM



          1) Opening a monitoring port on the remote Tomcat server, we added following java VM options at the startup script, 



          Export JAVA_OPTS="$JAVA_OPTS -Dcom.sun.management.jmxremote.port=19993 -Dcom.sun.management.jmxremote.authenticate=

          false -Dcom.sun.management.jmxremote.ssl=false"



          This requires firewall opening between the local pc and server on port specified 19993.



          2) There are two good tools for monitoring JVM, i.e. JConsole and VirtualVM. run these two appliation and login the remote server and the specified port, then you may monitor the VM state.



          JConsole is shipped with JDK after version 5. You may easily find it from JAVA_HOME/bin/jconsole.exe



          VisualVM is a third party software, which can be download from its official home.



          How to Reset Heap Memory Size



          Sometime the insuficent memory is just caused by the insufficent heap memory, so it need to reset the memory size.The Java Virtual Machine takes two command line arguments which set the initial and maximum heap sizes:



          -Xms and -Xmx. For example if you want to give your Java program needs a 128Mb initial and 256Mb maximum heap size you could launch it as follows:



          JAVA_OPTS="-server -Xms128M -Xmx256M"



           



          Set HeapDumpOnOutOfMemoryError Option



          set JAVA_OPTS=%JAVA_OPTS% -server -Xms512m -Xmx800m -XX:PermSize=64M -XX:MaxPermSize=128m -Djava.awt.headless=true -XX:+HeapDumpOnOutOfMemoryError -XX:+HeapDumpOnCtrlBreak



          A heap dump file will be generated in /bin folder, when out of memory happens.



          The -XX:+HeapDumpOnOutOfMemoryError command-line option was introduced in Java SE release


          5.0 update 7. This option tells the HotSpot VM to generate a heap dump when the first thread throws a


          java.lang.OutOfMemoryError because the Java heap or the permanent generation is full. There is


          no overhead in running with this option, and so it can be useful for production systems where


          OutOfMemoryError takes a long time to surface.


          The heap dump is in HPROF binary format, and so it can be anaylzed by any tool that can import this


          format, for example the Heap Analysis Tool (HAT).


          By default the heap dump is created in a file called java_pid<pid>.hprof in the working directory


          of the VM, where <pid> is the process ID. You can specify an alternative file name or directory with


          the -XX:HeapDumpPath= option. For example, -XX:HeapDumpPath=/disk2/dumps will cause the


          heap dump to be generated in the /disk2/dumps directory.



          How to monitor JVM



          Using jconsole



          I sent several banches of data to the debitorregisterweb, and it seems that there are some heap memory that cannot be released afterwards, the used the heap space increased step by step, where is the gc operation,



          How to fix memory leak



          http://java.dzone.com/news/how-fix-memory-leaks-java



          How profile Java application in VirtualVM



          VisualVM - tool for profiling Java applications

          Wednesday, 2 September 2009

          Setup Jconsole Remotely Monitoring Memory Leak

          JVM Arguments

          J2SE 1.5.0_06
          # Memory configuration
          JAVA_OPTS="-server"
          JAVA_OPTS="$JAVA_OPTS -Xms1280m"
          JAVA_OPTS="$JAVA_OPTS -Xmx1280m"
          JAVA_OPTS="$JAVA_OPTS -XX:NewSize=640m"
          JAVA_OPTS="$JAVA_OPTS -XX:MaxNewSize=640m"
          JAVA_OPTS="$JAVA_OPTS -XX:SurvivorRatio=5"
          JAVA_OPTS="$JAVA_OPTS -XX:TargetSurvivorRatio=90"
          JAVA_OPTS="$JAVA_OPTS -XX:MaxTenuringThreshold=12"
          JAVA_OPTS="$JAVA_OPTS -XX:+UseConcMarkSweepGC"
          JAVA_OPTS="$JAVA_OPTS -XX:+CMSIncrementalMode"
          JAVA_OPTS="$JAVA_OPTS -XX:+CMSIncrementalPacing"
          JAVA_OPTS="$JAVA_OPTS -XX:+CMSParallelRemarkEnabled"
          JAVA_OPTS="$JAVA_OPTS -XX:+UseParNewGC"
          JAVA_OPTS="$JAVA_OPTS -XX:PermSize=64m"
          JAVA_OPTS="$JAVA_OPTS -XX:MaxPermSize=64m"
          JAVA_OPTS="$JAVA_OPTS -XX:+UseTLAB"
          # Enable class unloading (needed with ConcMarkSweepGC
          JAVA_OPTS="$JAVA_OPTS -XX:+CMSClassUnloadingEnabled"
          JAVA_OPTS="$JAVA_OPTS -XX:+CMSPermGenSweepingEnabled"
          # debug and memory tweaks to avoid Hotspot Compiler Failure
          JAVA_OPTS="$JAVA_OPTS -XX:+PrintCompilation"
          JAVA_OPTS="$JAVA_OPTS -XX:CodeCacheMinimumFreeSpace=2M"
          JAVA_OPTS="$JAVA_OPTS -XX:ReservedCodeCacheSize=64M"
          JAVA_OPTS="$JAVA_OPTS -XX:CompileCommandFile=/my/portal/bin/hotspot_compiler"
          # Enable JMX Remote Monitoring
          JAVA_OPTS="$JAVA_OPTS -Dcom.sun.management.jmxremote"
          JAVA_OPTS="$JAVA_OPTS -Dcom.sun.management.jmxremote.port=9000"
          JAVA_OPTS="$JAVA_OPTS -Dcom.sun.management.jmxremote.ssl=false"
          JAVA_OPTS="$JAVA_OPTS -Dcom.sun.management.jmxremote.password.file=/my/portal/bin/jmxremote.password"
          JAVA_OPTS="$JAVA_OPTS -Dcom.sun.management.jmxremote.access.file=/my/portal/bin/jmxremote.access"
          # turn on some debug for GC only print the distribution when doing tuning
          JAVA_OPTS="$JAVA_OPTS -verbose:gc"
          JAVA_OPTS="$JAVA_OPTS -XX:+PrintGCTimeStamps"
          JAVA_OPTS="$JAVA_OPTS -XX:+PrintGCDetails"
          #JAVA_OPTS="$JAVA_OPTS -XX:+PrintTenuringDistribution"
          JAVA_OPTS="$JAVA_OPTS -Xloggc:/my/portal/logs/portal/gc.log"
          # Enable remote debugging port
          JAVA_OPTS="$JAVA_OPTS -Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n"

          Can Jackson Deserialize Java Time ZonedDateTime

          Yes, but must include JSR310. Thus ZonedDateTime can be deserialized directly from JSON response to POJO field. <dependency> <g...