Showing posts with label JAVA. Show all posts
Showing posts with label JAVA. Show all posts

Wednesday, August 28, 2013

Runtime instrumentation of bytecode using javaagent with Javassist

I was looking into some classloading issues of websphere application server and encountered with javaagent argument , I found really interesting when i read "The agent class will be loaded by the same classloader which loads the class containing the application main method.", and i started digging more into it.

This was a new thing for me. I used the transformer to see a class loaded from which location. I was doing the same from debugger for multiple class was really time consuming. By using transformer i could find out easily a class was loaded by whicih classloader and from which location using ProtectionDomain, etc. Co-incidently I was working on profiling also and found it can be used there as well.

I wrote small program around it and found it is useful. Many people have written already written in this area but did not find on any blog quickly that how to get a count for method execution, so i thought it writing myself. Of-course many tools like Jensor, Jrat, etc, gives lot more facility but i did it just to get method count and not any other reporting.

So ultimately this blog post covers

  • Javaagent and premain
  • ClassFileTransformer
  • Javassist



  • Javaagent and premain: Introduced in JDK 5, vm argument.. Can augument java bytecode dynamically with the transformer(s) which helps in profiling, bytecode manupulation,. With this dynamic manipulation we can manipulate bytecode during the runtime and which is one of the most useful feature of java. Agent can be added in the JVM argument for your program or server. Agent must implement premain method. 
         A premain method is the one which gets executed before loading the class and before executing main
         method in the class. Javaagent can be added as the JVM argument as follows:

        -javaagent: for e.g. -javaagent:D:\Instrumentation\dsinstrumentation.jar





  • ClassFileTransformer: Agent can add one or more transformer, we have to implement ClassFileTransformer interface. Transformed class which is responsible for transformation of the bytecode. The transformation occurs before the class is defined by the JVM.

          jar which we add as a jarpath for javaagent argument, must have Premain-Class attribute in
          MANIFEST.MF file. Which is as follows




  • Javassist: I have used Javassist for byte code instrumentation. We have multiple choices to achive the same. Users can use Javassist, ASM, BCEL from apache, etc.



You can find/download the source code from my github account repository which included dsinstrumentation.jar as well, which can be used directly.
User need to provide
a) -javaagent
b) configuration system property which should have conf folder with the classinstrumentation.properties file
with the class file name in the following format:



Download : git repository for instrumentation

To run dsinstrumentaion.jar (which is available in the above mentioned download location) as javaagent, give the following jvm argument

-javaagent:<FOLDER_PATH_TO_INSTRUMENTATION_JAR>\dsinstrumentation.jar
-Dconfiguration=<FOLDER_PATH_TO_CONF_FOLDER>\conf

Friday, January 25, 2013

Realization of dream of multitenancy with Google App Engine and MongoDB on cloud.

Multitenancy and the problem of managing the data

Multitenancy refers to a principle in software architecture where a single instance of the software runs on a server, serving multiple client organizations (tenants). Multitenancy is contrasted with a multi-instance architecture where separate software instances (or hardware systems) are set up for different client organizations. With a multitenant architecture, a software application is designed to virtually partition its data and configuration, and each client organization works with a customized virtual application instance. [WIKI]

What if i want to migrate my existing system to any cloud engine?
Move all of code/business logic to app engine, perfect, no problem, but what if my database is already on another physical infrastructure(and which is shredded,etc)?


Of-course app engine/GAE gives you the ability to scale, security, high availability, etc. but with their own terms.You need to use the database which is supported only by the app engine.
Which is one of the major drawback for the GAE and similarly other cloud engines.

I wanted to use MongoDB with Google App Engine(GAE) and could not see the possibility because we can't run MongoDB on GAE and supposed to use Google datastore.

There are few more issues as GAE's highly restricted sandbox. As GAE's docs says your application can only access other computers on the internet through the provided URL fetch and email services (and fewer more ways). Other computers can only connect to the application by making HTTP/HTTPS requests on the standard port. If you want to open a socket from your business logic, its not allowed and GAE will raise an exception.

Few good things happened in this direction, when google annoucned back in 2011 about Google Cloud SQL webservice to support MySQL - https://developers.google.com/cloud-sql/
Some of the other cloud engines have provided more options such as Amazon RDS supports MySQL, Oracle or Microsoft SQL Server database engine. This means that the code, applications, and tools you already use today with your existing databases can be used with Amazon RDS.

I was adamant to move from MongoDB and to use my application with the GAE and mongolab became the savior. Why i want to use my own choice of database because i have already have my own hosted database servers because i want to manage data on my own (security reason, business reason, etc)

Here is the steps how can we use GAE with MongoDB, when your MongoDB instance is hosted on DB cloud.

1) Signup, login and create a database on mongolab


This is going to create mongodb as the database.


2) Create a collection
    Creation of collection (table) can be done by going to database and click on "Add".

3) Open collection which is currently empty and open the API view.
    Connection information on the top of the "Collections" tab is the url which we are going to use interact
    with "mongodb" database created in step1, mongolab has provided REST based methods for database
    interactions.



    At this point we are done with our database part.

    Lets move to GWT(Google Web Toolkit) to create a project.

4) Create a Web Application Project and make sure that "Use Google App Engine" is checked.


    Create a GWT based application, i have used the almost same application which i have created earlier,
    you can refer the steps for the application creation here GWT RPC - Server communication with 
    MongoDB

    The only change here is that the mongodb is hosted on some cloud, and because of that implementation
    for is going to change.

5) Insert a recod and retrive records from cloud database.
    Inserting a record into the databased using the apache's HTTPClient to connect to mongodb hosted on
    cloud, which interacts with the REST based webservice.



    Get all available users from the database.


   As i mentioned earlier about the sandbox security of GAE, i could not use HttpClient directly to invoke
   webserivce and get the data, and had to tweak it bit to make it happen. Shortly going to update about the
  problem as well in this post, which will be describing about GAEConnectionManager.

6) In order to deploy the developed application on cloud, create an an application identifier on app engine.  
    After creation you can see the application as follows:


    Update in /war/WEB-INF/appengine-web.xml and place it under "application" tag.



7) Login to google account from eclipse(you can find it in the bottom left) and deploy the app on the app
    engine.




   And we are done!,  app is available and hosted.
   You can access it from here: http://mongocloudapp.appspot.com/

    I would like to say that overall it is a very nice experience with the app development with GAE and
    without loosing the my own preferred database.

Monday, August 6, 2012

GWT Editable Table - CellTable with remove row


GWT offers table where we can specify column types, and make rows data modifiable.

CellTable supports paging and columns, i have not used paging in this example but only specified the columns for text and button.




The Column class defines the Cell used to render a column.

Implement Column.getValue(Object) to retrieve the field value from the row object that will be rendered in the Cell.



and the data which will be rendered:

You can use TextCell instead of EditTextCell, in case you do not want to make column editable.


DataProvider, ListDataProvider can display data which should be provided as list.

I have used modal User to create few items in the list and provide the same to the ListDataProvider and which works as the modal for the celltable.



Remove row from the dataProvider and table.


When user clicks on "x" update gets called from updater and where we can remove the row from the modal and refresh modal and re-draw table (i found without refresh modal and redraw table call also it was working fine).

Example files are available to download <<==== click here to download.
Look for GwtExamples.rar (v.1) 

Tuesday, July 24, 2012

GWT RPC - Server communication with MongoDB

Further to the client tutorial in the previous blog, here i am going to present how client communicates with the server with the help of GWT RPC (Remote Procedure Call).
Using RPC which works asynchronously only specific part of the client components can be updated without updating the complete client.














Pre-Requisite:
Java, Eclipse with GWT plugin, MongoDB.



In this example i have extended the previous client to
  a) save data i.e. user data to database and
  b) authentication user

Client can send/receive serializable objects to/from the server. In this example server is going to use that data and insert in into DB, which is MongoDB in our case.


Create Modal
As the client can send serializable java objects over HTTP. Lets create a modal first.


User.java



Create Service
Now we need to have a service which a client can use.
In our case we name it as MongoDBService and it implements RemoteService


MongoDBService.java



@RemoteServiceRelativePath("dbservice") is annotation used for the service identification and calling, which should match with the service path defined in web.xml for servlet-mapping tag.

We need to create Asynchronous service for our MongoDBService, client is actually going to call RPC through MongoDBServiceAsync. All methods of MongoDBService will have extra parameter which is of type AsyncCallback. Client call will be notified when any asynchronous service call completes.

MongoDBServiceAsync.java



Implement service at the server side
Create class MongoDBServiceImpl which extends RemoteServiceServlet and implements MongoDBService. Basically MongoDBServiceImpl is a servlet which is extending from RemoteServiceServlet rather than the HttpServlet directly.



Updating web.xml with servlet details
make sure that all the service which are created with the annotation RemoteServiceRelativePath are added properly for each servlet.

web.xml



url pattern tag path should be formed using module/service.
In this case module name is gwtwebappdemo ( see in GwtWebAppDemo.gwt.xml for rename-to value) and service in dbservice.


Client Service Call
calling service from client





Running application

1) Start MongoDB
    In this case i have started DB without authentication and on default port.
    Default port is 27017 which we have used to connect to database in the code. See DBUtil.java in the
   example.



2) Add user into database.
    Client calls asynchronous call to server, server starts the processing. Once request processing is finished it calls back with the call back handler provided in the request. Client gets call in onFailure in case of failure and onSuccess in case of request processing successful.


    In the server side, server received the User object and sets the data into User collection which is in the mymongodb database using BasicDBObject.

MongoDBServiceImpl.java


3) Check the collection ( table) creation in dbs (database)
    In this example mymongodb is the database and User is the collection which we are using.
    Initially both database and collection is not present, when the first save happens. Both gets automatically
    created.



4) Check User Authentication with wrong input.



Download complete example from here in GwtWebAppDemo_server.rar file.

Monday, December 6, 2010

How to make a non-serializable class serializable

I have a class which is not serializable. If i will try to serialize the object of it than i am going to get exception "java.io.NotSerializableException"

And now if this class is not not modifiable/available to modify (may be its a third party), and so we do not have any control.

for e.g following is the non serializable class
class MyNonSerializableClass {
 String str = new String("mystring");
 MyNonSerializableClass(){
  
 }
 MyNonSerializableClass(String s) {
  this.str = s;
 }

 public String getStr() {
  return str;
 }

 public void setStr(String str) {
  this.str = str;
 }

}



In order to serialize the object we can write a wrapper class over MyNonSerializableClass and which is implementing Serializable interface.
And the most important thing, we control the readObject and writeObject methods so that we can decide what need to be written with the wrapper class.

something like this:

class MyNonSerializableClassWrapper extends MyNonSerializableClass implements Serializable {
 MyNonSerializableClassWrapper(){
  super();
 }
 MyNonSerializableClassWrapper(String s) {
  super(s);
 }

 private void writeObject(ObjectOutputStream out) throws IOException {
  // not required the default write object
  // ----> out.defaultWriteObject();
  out.writeObject(super.getStr());
 }

 private void readObject(ObjectInputStream in) throws IOException {
  // not required the default read object
  // ----> in.defaultReadObject();
  try {
   super.setStr((String) in.readObject());
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  }
 }
}


As the wrapper class itself does not have any properties/attributes so defaultread and write is not required.
By getting the super class value and setting it during the write and read to serialized object we can achieve the serialization and deserialization even if a class is not implementing Serializable interface.


private void WriteObjectToFile() {
try {
  FileOutputStream fo = new FileOutputStream("c:\\test.ser");
  ObjectOutputStream os = new ObjectOutputStream(fo);
  os.writeObject(new MyNonSerializableClassWrapper("This is a test of 
                                           serialization"));
  fo.close();

  } 
  catch (FileNotFoundException e) {
    e.printStackTrace();
  } 
  catch (IOException e) {
    e.printStackTrace();
  }
}


private void ReadObjectFromFile() {
try {
  FileInputStream fi = new FileInputStream("c:\\test.ser");
  ObjectInputStream in = new ObjectInputStream(fi);
  MyNonSerializableClassWrapper mw = (MyNonSerializableClassWrapper) 
  in.readObject();
  fi.close();
  System.out.println("serialized object value is: " + mw.getStr());
  } 
  catch (FileNotFoundException e) {
      e.printStackTrace();
  } 
  catch (IOException e) {
    e.printStackTrace();
  } 
  catch (ClassNotFoundException e) {
    e.printStackTrace();
  }
}




Sunday, February 17, 2008

Aspect-Oriented Programming and Introduction to AspectJ


Aspect-Oriented ProgrammingIntroduction to AspectJ
Programming paradigms
• Procedural programming
– Executing a set of commands in a given sequence
– Fortran, C, Cobol
• Functional programming
– Evaluating a function defined in terms of other functions
– Lisp, ML, OCaml
• Logic programming
– Proving a theorem by finding values for the free variables
– Prolog
• Object-oriented programming (OOP)
– Organizing a set of objects, each with its own set of responsibilities
– Smalltalk, Java, C++ (to some extent)
• Aspect-oriented programming (AOP)
– Executing code whenever a program shows certain behaviors
– AspectJ (a Java extension)
– Does not replace O-O programming, but rather complements it



Introduction• Currently, the dominant programming paradigm is object-oriented programming that:
• Object orientation is a clever idea, but has certain limitations
• has been presented as a technology that can fundamentally aid software engineering
• is reflected in the entire spectrum of current software development methodologies and tools


Introduction AOP
• A new programming technique called aspect-oriented programming (AOP):
- makes it possible to clearly express those programs that OOP fail to support
- enables the modularization of crosscutting concerns by supporting a new unit of

software modularity – aspects – that provide encapsulation for crosscutting concerns

What are aspects?• The current working definition is (May 99, Gregor Kiczales):
- modular units that cross-cut the structure of other modular units
- units that is defined in terms of partial information from other units
- exist in both design and implementation

Aspect: A distinct feature or element in a problem

Concerns• AOP is based on the idea that computer systems are better programmed by separately specifying the various concerns of a system
• Separation of concerns is an important software engineering principle guiding all stage of a software development methodology
• Concerns:
are properties or areas of interest
can range from high-level notion to low level-notion
can be functional or nonfunctional (systemic)

The problem
• Some programming tasks cannot be neatly encapsulated in objects, but must be scattered throughout the code
• Examples:
– Logging (tracking program behavior to a file)
– Profiling (determining where a program spends its time)
– Tracing (determining what methods are called when)
– Session tracking, session expiration
– Special security management
• The result is crosscuting code--the necessary code “cuts across” many different classes and methods


Example
class Fraction {
int numerator;
int denominator;
...
public Fraction multiply(Fraction that) {
traceEnter("multiply", new Object[] {that});
Fraction result = new Fraction( this.numerator * that.numerator, this.denominator * that.denominator);
result = result.reduceToLowestTerms();
traceExit("multiply", result);
return result;
}
...
}
Now imagine similar code in every method you might want to trace



Consequences of crosscutting code• Redundant code
– Same fragment of code in many places
• Difficult to reason about
– Non-explicit structure
– The big picture of the tangling isn’t clear
• Difficult to change
– Have to find all the code involved...
– ...and be sure to change it consistently
– ...and be sure not to break it by accident
• Inefficient when crosscuting code is not needed

AspectJTM
• AspectJ is a small, well-integrated extension to Java
– Based on the 1997 PhD thesis by Christina Lopes, A Language Framework for Distributed Programming
• AspectJ modularizes crosscutting concerns
– That is, code for one aspect of the program (such as tracing) is collected together in one place
• The AspectJ compiler is free and open source
• AspectJ works with JBuilder, Forté, Eclipse, probably others
• Best online writeup: http://www.eclipse.org/aspectj/


Terminology• A join point is a well-defined point in the program flow
• A pointcut is a group of join points
• Advice is code that is executed at a pointcut
• Introduction modifies the members of a class and the relationships between classes
• An aspect is a module for handling crosscutting concerns
– Aspects are defined in terms of pointcuts, advice, and introduction
– Aspects are reusable and inheritable
• Each of these terms will be discussed in greater detail
The Figure Element example




Using Objects• Expressive
– What is going on its clear
• Abstraction
– Focus on more or less detail
• Structure & Modularity
– What goes where
– How parts fit together
–Things are pretty clear, you know every thing about it. If you wanna add new shapes(FigureElement) that also you can add.
–So now lets make it probelamatic… how… Simple Observer Pattern
–If there is any change in the shape…. Drawing Object should be notified.
–So what is this , good design but a worst code.
–So what can we do , we can use aspects , we can have a aspect for observer pattern and which will be weaved with the existing codess and proviides use the way to work with new requirements.
–So we have Good Design and Good Code.
–Lets see how to do that with the help of aspects.



Other Aspects
• Security
– Pointcut for when checking happens
• Optimization
• Distribution
• Synchronization
• Persistance
• And ofcourse Logging/Tracing
• And very many application –specific aspects
- i.e EnsureLiveness

Example I• A pointcut named move that chooses various method calls:
pointcut move(): call(void FigureElement.setXY(int,int))||
call(void Point.setX(int))||
call(void Point.setY(int))||
call(void Line.setP1(Point))||
call(void Line.setP2(Point));||

• Advice (code) that runs before the move pointcut:
before(): move() {
System.out.println("About to move");
}
• Advice that runs after the move pointcut:
after(): move() {
System.out.println("Just successfully moved");
}
Join points
• A join point is a well-defined point in the program flow
– We want to execute some code (“advice”) each time a join point is reached
– AspectJ provides a syntax for indicating these join points “from outside” the actual code
• A join point is a point in the program flow “where something happens”
– Examples:
• When a method is called
• When an exception is thrown
• When a variable is accessed

AspectJ supports 11 different kinds of join points.These are the method call, method execution, constructor call, constructor execution, field get, field set, pre initialization, initialization, static initialization, handler, and advice execution join points.
Pointcuts
• Pointcut definitions consist of a left-hand side and a right-hand side, separated by a colon
– The left-hand side consists of the pointcut name and the pointcut parameters (i.e. the data available when the events happen)
– The right-hand side consists of the pointcut itself
• Example pointcut:pointcut setter(): call(void setX(int));
– The name of this pointcut is setter
– The pointcut has no parameters
– The pointcut itself is call(void setX(int))
– The pointcut refers to any time the void setX(int) method is called
Example pointcut designators I
• When a particular method body executes:
– execution(void Point.setX(int))
• When a method is called:
– call(void Point.setX(int))
• When an exception handler executes:
– handler(ArrayOutOfBoundsException)
• When the object currently executing (i.e. this) is of type SomeType:
– this(SomeType)



Example pointcut designators II• When the target object is of type SomeType
– target(SomeType)
• When the executing code belongs to class MyClass
– within(MyClass)
• When the join point is in the control flow of a call to a Test's no-argument main method
– cflow(call(void Test.main()))
Pointcut designator wildcards
• It is possible to use wildcards to declare pointcuts:
– execution(* *(..))
• Chooses the execution of any method regardless of return or parameter types
– call(* set(..))
• Chooses the call to any method named set regardless of return or parameter type
• In case of overloading there may be more than one such set method; this pointcut picks out calls to all of them
Pointcut designators based on types
• You can select elements based on types. For example,
– execution(int *())
• Chooses the execution of any method with no parameters that returns an int
– call(* setY(long))
• Chooses the call to any setY method that takes a long as an argument, regardless of return type or declaring type
– call(* Point.setY(int))
• Chooses the call to any of Point’s setY methods that take an int as an argument, regardless of return type
– call(*.new(int, int))
• Chooses the call to any classes’ constructor, so long as it takes exactly two ints as arguments
Pointcut designator composition
• Pointcuts compose through the operations or (“”), and (“&&”) and not (“!”)
• Examples:
– target(Point) && call(int *())
• Chooses any call to an int method with no arguments on an instance of Point, regardless of its name
– call(* *(..)) && (within(Line) within(Point))
• Chooses any call to any method where the call is made from the code in Point’s or Line’s type declaration
– within(*) && execution(*.new(int))
• Chooses the execution of any constructor taking exactly one int argument, regardless of where the call is made from
– !this(Point) && call(int *(..))
• Chooses any method call to an int method when the executing object is any type except Point
Pointcut designators based on modifiers• call(public * *(..))
– Chooses any call to a public method
• execution(!static * *(..))
– Chooses any execution of a non-static method
• execution(public !static * *(..))
– Chooses any execution of a public, non-static method
• Pointcut designators can be based on interfaces as well as on classes
Example I, repeated
• A pointcut named move that chooses various method calls:
pointcut move(): call(void FigureElement.setXY(int,int))
call (void Point.setX(int))
call(void Point.setY(int))
call(void Line.setP1(Point))
call(void Line.setP2(Point));

• Advice (code) that runs before the move pointcut:
before(): move() {
System.out.println("About to move");
}

• Advice that runs after the move pointcut:
after(): move() {
System.out.println("Just successfully moved");
}

Kinds of advice
AspectJ has several kinds of advice; here are some of them:
– Before advice runs as a join point is reached, before the program proceeds with the join point
– After advice on a particular join point runs after the program proceeds with that join point
• after returning advice is executed after a method returns normally
• after throwing advice is executed after a method returns by throwing an exception
• after advice is executed after a method returns, regardless of whether it returns normally or by throwing an exception
– Around advice on a join point runs as the join point is reached, and has explicit control over whether the program proceeds with the join point

Example II, with parameters• You can access the context of the join point:
• pointcut setXY(FigureElement fe, int x, int y): call(void FigureElement.setXY(int, int)) && target(fe) && args(x, y);
• after(FigureElement fe, int x, int y) returning: setXY(fe, x, y) { System.out.println(fe + " moved to (" + x + ", " + y + ").");}


Introduction
• An introduction is a member of an aspect, but it defines or modifies a member of type (class). With introduction we can
– add another methods to an existing class
– add fields to an existing class
– extend an existing class with another
– implement an interface in an existing class
– convert checked exceptions into unchecked exceptions

Example introductionpublic aspect CloneSimpleClass {
declare parents: SimpleClass2 implements Cloneable;
declare soft: CloneNotSupportedException: execution(Object clone());
public Object SimpleClass2.clone(){ return super.clone();}
}

/*
* 1. Class which does not implement CloneNotSupportedException, expected output is
* sucessful running of the method calls because we have aspect for cloning.
*/
public class SimpleClass2 {
private String name=null;
public SimpleClass2(String s){
name = s;
}
public static void main(String[] args) {
SimpleClass2 ref1 = new SimpleClass2("Demo");
ref1.funtion();
try {
SimpleClass2 ref2 = (SimpleClass2) ref1.clone();
ref2.funtion();
} catch (Exception e) {
e.printStackTrace();
}
}
private void funtion() {
System.out.println("Name is "+name);
}
}
So what this does, it adds a functionality for cloning to a non
Cloneable class. Deciding about the feature enancement
during runtime …. Amazing capability in the product….



Approximate syntax
• An aspect is: aspect nameOfAspect { body }
– An aspect contains introductions, pointcuts, and advice
• A pointcut designator is: when(signature)
– The signature includes the return type
– The “when” is call, handler, execution, etc.
• A named pointcut designator is: name(parameters): pointcutDesignator
• Advice is: adviceType(parameters): pointcutDesignator { body }
• Introductions are basically like normal Java code
Example aspect I• aspect PointWatching {
private Vector Point.watchers = new Vector();
public static void addWatcher(Point p, Screen s) { p.Watchers.add(s); }
public static void removeWatcher(Point p, Screen s) { p.Watchers.remove(s); }
static void updateWatcher(Point p, Screen s) { s.display(p); }

pointcut changes(Point p): target(p) && call(void Point.set*(int));
after(Point p): changes(p) {
Iterator iter = p.Watchers.iterator();
while ( iter.hasNext() ) {
updateWatcher(p, (Screen)iter.next());
} }}

How to identify which aspect is working


• In case of Introduction, which we applied to SimnpleClass2, aspect scope is for the class







The role of aspects in software design
• AOP aims at providing better means of addressing the well-known problem of separation of concerns
• Three basic approaches to addressing the process of separation of concerns:
Language-based approach• It is based on the definition of a set of language constructs
• Relevant concerns are identified at the problem domain and translated to aspectual construct
• The final application is obtained by weaving the primary structure with the crosscutting aspects
Framework-based approach• Provides more flexible constructs
• Concerns are materialized as aspectual classes at the framework level
• Developers can customize these aspects using the mechanism supported by the framework
• These types of framework are known as AO frameworks (explicitly engineers concerns)
Architecture-oriented approach• Early identification of concerns using architectural organizational models
• Architectural view-point involves a higher level of abstraction than the previous approaches
• It typically comprises two stages
Architecture-oriented approach
• First, developers should determine the problem architecture
• Then, the approach enables several kinds of aspect materialization through different frameworks



Concluding remarks• Aspect-oriented programming (AOP) is a new paradigm--a new way to think about programming
• AOP is somewhat similar to event handling, where the “events” are defined outside the code itself
• AspectJ is not itself a complete programming language, but an adjunct to Java
• AspectJ does not add new capabilities to what Java can do, but adds new ways of modularizing the code
• AspectJ is free, open source software
• AspectJ based on Java Features and which includes
– Annotations
– Generics
– Enumerated Types
– AutoBoxing and UnBoxing
– New Reflection Interfaces
– Load Time Weaving


Will be adding few exampls ............. shortly..........

Saturday, January 19, 2008

Java Tips for ...novice programmers...

Object-Oriented Programming• An abstract method cannot (obviously) be final.
• An abstract method cannot be static because static methods cannot be
overridden.
• An instance method can be both protected and abstract. A static method
can be protected.
• The JVM does not call an object’s constructor when you clone the object.
• Classes can be modified from their default state using any of the three
keywords: public, abstract, and final. So, can’t have a static class,
only static methods.
• A final variable is a constant, and a final method cannot be overridden.
• A call to this in a constructor must also be on the first line.
Note: can’t have an explicit call to super followed by a call to this
in a constructor - only one direct call to another constructor is allowed.


Memory and Garbage Collection• Can’t predict when garbage collection will occur, but it does run
whenever memory gets low.
• If you want to perform some task when your object is about to be
garbage collected, you can override the java.lang.Object method called
finalize(). This method is declared as protected, does not return a value,
and throws a Throwable object, i.e. protected void finalize() throws Throwable.
• Always invoke the superclass’s finalize() method if you override finalize().
• The JVM only invokes finalize() once per object. Since this is the case,
do not resurrect an object in finalize as when the object is finalized
again its finalize() method will not be called. Instead you should create a
clone of the object if you must bring the object back to life.
• Remember that Java passes method parameters by value and not by
reference. Obviously then, anything that happens to a primitive data
type inside a method does not affect the original value in the calling code.
Also, any reassignment of object references inside a method has no effect
on the objects passed in.


Exceptions
• Invoking a method which declares it throws exceptions is not
possible unless either the code is placed in a try-catch, or the calling
method declares that it throws the exceptions, i.e. checked
exceptions must be caught or rethrown. If the try-catch
approach is used, then the try-catch must cope with all of the
exceptions which a method declares it throws.
• RuntimeException and its subclasses are unchecked exceptions.
• Unchecked exceptions do not have to be caught.
• All Errors are unchecked.
• You should never throw an unchecked exception in your own code, even
though the code will compile.

Methods

• A native method does not have a body, or even a set of braces,
e.g. public native void method();
• A native method cannot be abstract.
• A native method can throw exceptions.
• A subclass may make an inherited method synchronized, or it may
leave offthe synchronized keyword so that its version is not synchronized.
If a methodin a subclass is not synchronized but the method in the
superclass is, the threadobtains the monitor for the object when it enters
the superclass’s method.• You cannot make a method in a subclass more
private than it is defined in thesuperclass, ‘though you can make it more public.


Threads

• A Java program runs until the only threads left running are daemon threads.
• A Thread can be set as a user or daemon thread when it is created.
• In a standalone program, your class runs until your main() method
exists - unless your main() method creates more threads.
• You can initiate your own thread of execution by creating a Thread
object, invoking its start() method, and providing the behaviour that
tells the thread what to do. The thread will run until its run() method
exists, after which it will come to a halt - thus ending its life cycle.
• The Thread class, by default, doesn’t provide any behaviour for run().
• A thread has a life cycle. Creating a new Thread instance puts the thread
into the "new thread" state. When the start() method is invoked, the
thread is then "alive" and "runnable". A thread at this point will repond
to the method isAlive () by returning true.
• The thread will continue to return true to isAlive() until it is "dead",
no matter whether it is "runnable" or "not runnable".
• There are 3 types of code that can be synchronized: class methods, i
nstance methods, any block of code within a method.
• Variables cannot take the synchronized keyword.
• Synchronization stays in effect if you enter a synchronized method
and call out to a non-synchronized method. The thread only gives
up the monitor after the synchronized method returns.



Inner Class

• If you define an inner class at the same level as the enclosing class’
instance variables, the inner class can access those instance variables -
no matter what their access control.
• If you define an inner class within a method, the inner class can
access the enclosing class’ instance variables and also the local
variables and parameter for that method.
• If you do reference local variables or parameters from an inner
class, those variables or parameters must be declared as final to
help guarantee data integrity.
• You can also define an anonymous class - a class without a name.
• If you’d like to refer to the current instance of the enclosing class,
you can write EnclosingClassName.this.
• If you need to refer to the inner class using a fully qualified name,
you can write EnclosingClassName.InnerClassName.
• If your inner class is not defined as static you can only create new
instances of this class from a non-static method.
• Anonymous classes cannot have const


Serializing Objects

•It is now possible to read and write objects as well as primitive data
types, using classes that implement ObjectInput and ObjectOutput.
These two interfaces extend DataInput and DataOutput to read or
write an object. ObjectInputStream and ObjectOutputStream
implement these interfaces.
• If a class implements the Serializable interface, then its public and
protected instance variables will be read from and written to the
stream automatically when you use ObjectInputStream and
ObjectOutputStream.
• If an instance variable refers to another object, it will also be
read or written, and this continues recursively.
• If the referenced object does not implement the Serializable
interface, Java will throw a NotSerializableException.
• The Serializable interface serves only to identify those instances
of a particular class that can be read from and written to a stream.
It does not actually define any methods that you must implement.
• If you create your own class and want to keep certain data from
being read or written, you can declare that instance variable
using the transient keyword. Java skips any variable declared as
transient when it reads and writes the object following the Serializable
protocol.


Reflection

• Using the Reflection API, a program can determine a class’ accessible
fields, methods and constructors at runtime.


will be adding moreeeeeeeeeeeee later, guys....... you are also free to add comments on this and more points........

Friday, December 14, 2007

MVC and Swing

The Model-View-Controller (MVC) architecture factors function code from the GUI design using a controller module. The controller module ties event listeners in the view module to their actions in the model module. Good programming practice implies private properties with public accessor methods for those needing access from outside their container object. These three object modules can be designed at different times by different programmers.

The well-known MVC paradigm is generally recommended as the fundamental architecture for GUI development. Many variations of the pattern are available, like MVC++, HMVC (Hierarchical MVC), MVC Model 2, MVC Push, and MVC Pull, with each emphasizing slightly different issues.

The model object should have methods for run(), about(), help(), and exit() as these are common to most utilities. The view object constructor should accept a string that incorporates the utility title. The view object also requires methods to build the listeners. buttonActionListeners() includes addActionListener() and a setActionCommand(string) which is used to pass a reference of the pressed button. The controller module uses getActionCommand() to call the correct action method in the model. An example of MVC architecture using the MyGUI example is:



/**

* @author Deepak Singhvi

* @version v7.4

*/



import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

/* myGUI demonstrates separation of functionality

from GUI design by using MVC architecture */



// first comes the root class that builds the architecture

public class MyGUI {



public static void main(String args[]) {

MyGUIModel model = new MyGUIModel();

MyGUIView view = new MyGUIView("myGUI MVC Demo");

MyGUIController controller = new MyGUIController(model, view);

}

}



// the model is where functionality (ie properties & methods) goes

class MyGUIModel {



public void exit() {

System.exit(0);

}



public void run() {

JOptionPane.showMessageDialog(null, "Deepak hear you!",

"Message Dialog", JOptionPane.PLAIN_MESSAGE);

}

}



// the view is where the GUI is built

class MyGUIView extends JFrame {



JButton run = new JButton("Run the Utility");

JButton exit = new JButton("Exit After Save");

JPanel buttons = new JPanel(new GridLayout(4, 1, 2, 2));



MyGUIView(String title) // the constructor

{

super(title);

setBounds(100, 100, 250, 150);

setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);

buttons.add(run);

buttons.add(exit);

this.getContentPane().add("Center", buttons);

setVisible(true);

}



//method to add ActionListener passed by Controller to buttons

public void buttonActionListeners(ActionListener al) {

run.setActionCommand("run");

run.addActionListener(al);

exit.setActionCommand("exit");

exit.addActionListener(al);

}

}



// the controller listens for actions and reacts

class MyGUIController implements ActionListener {



MyGUIModel model;

MyGUIView view;



public MyGUIController(MyGUIModel model, MyGUIView view) {

  // create the model and the GUI view

  this.model = model;

  this.view = view;

  // Add action listener from this class to buttons of the view

  view.buttonActionListeners(this);

}



// Provide interactions for actions performed in the view.

public void actionPerformed(ActionEvent ae) {

  String action_com = ae.getActionCommand();

  char c = action_com.charAt(0);

  switch (c) {

    case'r':

      model.run();

      break;
 
    case'e':

      model.exit();

      break;

    }

  }

}





Friday, November 2, 2007

Common causes for memory leaks in Java applications

1) Unbounded caches
A very simple example of a memory leak would be a java.util.Collection object (for example, a HashMap) that is acting as a cache but which is growing without any bounds.

public class MyClass {
static HashSet myContainer = new HashSet();
public void leak(int numObjects) {
for (int i = 0; i < numObjects; ++i) {
String leakingUnit = new String("this is leaking object: " + i);
myContainer.add(leakingUnit);
}
}
public static void main(String[] args) throws Exception {
{
MyClass myObj = new MyClass();
myObj.leak(100000); // One hundred thousand
}
System.gc();
}


In the above program, there is a class with the name MyClass which has a static reference to HashSet by the name of myContainer. In the main method of the class: MyClass, (in bold text) within which an instance of the class: MyClass is instantiated and its member operation: leak is invoked. This results in the addition of a hundred thousand String objects into the container: myContainer. After the program control exits the subscope, the instance of the MyClass object is garbage collected, because there are no references to that instance of the MyClass object outside that subscope. However, the MyClass class object has a static reference to the member variable called myContainer. Due to this static reference, the myContainer HashSet continues to persist in the Java heap even after the sole instance of the MyClass object has been garbage collected and, along with the HashSet, all the String objects inside the HashSet continue to persist, holding up a significant portion of the Java heap until the program exits the main method.

This program demonstrates a basic memory leaking operation involving an unbounded growth in a cache object. Most caches are implemented using the Singleton pattern involving a static reference to a top level Cache class as shown in this example.


Here is the GC information for you for the above snippet....

[GC 512K->253K(1984K), 0.0018368 secs]
[GC 765K->467K(1984K), 0.0015165 secs]
[GC 979K->682K(1984K), 0.0016116 secs]
[GC 1194K->900K(1984K), 0.0015495 secs]
[GC 1412K->1112K(1984K), 0.0015553 secs]
[GC 1624K->1324K(1984K), 0.0014902 secs]
[GC 1836K->1537K(2112K), 0.0016068 secs]
[Full GC 1537K->1537K(2112K), 0.0120419 secs]
[GC 2047K->1824K(3136K), 0.0019275 secs]
[GC 2336K->2035K(3136K), 0.0016584 secs]
[GC 2547K->2248K(3136K), 0.0015602 secs]
[GC 2760K->2461K(3136K), 0.0015517 secs]
[GC 2973K->2673K(3264K), 0.0015695 secs]
[Full GC 2673K->2673K(3264K), 0.0144533 secs]
[GC 3185K->2886K(5036K), 0.0013183 secs]
[GC 3398K->3098K(5036K), 0.0015822 secs]
[GC 3610K->3461K(5036K), 0.0028318 secs]
[GC 3973K->3673K(5036K), 0.0019273 secs]
[GC 4185K->3885K(5036K), 0.0019377 secs]
[GC 4397K->4097K(5036K), 0.0012906 secs]
[GC 4609K->4309K(5036K), 0.0017647 secs]
[GC 4821K->4521K(5036K), 0.0017731 secs]
[Full GC 4521K->4521K(5036K), 0.0222485 secs]
[GC 4971K->4708K(8012K), 0.0042461 secs]
[GC 5220K->4920K(8012K), 0.0018258 secs]
[GC 5432K->5133K(8012K), 0.0018648 secs]
[GC 5645K->5345K(8012K), 0.0018069 secs]
[GC 5857K->5558K(8012K), 0.0017825 secs]
[GC 6070K->5771K(8012K), 0.0018911 secs]
[GC 6283K->5984K(8012K), 0.0016350 secs]
[GC 6496K->6197K(8012K), 0.0020342 secs]
[GC 6475K->6312K(8012K), 0.0013560 secs]
[Full GC 6312K->6118K(8012K), 0.0341375 secs]
[GC 6886K->6737K(11032K), 0.0045417 secs]
[GC 7505K->7055K(11032K), 0.0027473 secs]
[GC 7823K->7374K(11032K), 0.0028045 secs]
[GC 8142K->7693K(11032K), 0.0029234 secs]
[GC 8461K->8012K(11032K), 0.0027353 secs]
[GC 8780K->8331K(11032K), 0.0027790 secs]
[GC 9099K->8651K(11032K), 0.0028329 secs]
[GC 9419K->8970K(11032K), 0.0027895 secs]
[GC 9738K->9289K(11032K), 0.0028037 secs]
[GC 10057K->9608K(11032K), 0.0028161 secs]
[GC 10376K->9927K(11032K), 0.0028482 secs]
[GC 10695K->10246K(11032K), 0.0028858 secs]
[GC 11014K->10565K(11416K), 0.0029284 secs]
[Full GC 10565K->10565K(11416K), 0.0506198 secs]
[GC 11781K->11071K(18956K), 0.0035594 secs]
[GC 12287K->11577K(18956K), 0.0042315 secs]
[GC 12793K->12082K(18956K), 0.0043194 secs]
[GC 12843K->12390K(18956K), 0.0030633 secs]
[GC 13606K->13494K(18956K), 0.0085937 secs]
[Full GC 13782K->13613K(18956K), 0.0646513 secs]




2) Infinite Loops

Some memory leaks occur due to program errors in which infinite loop in the application code allocates new objects and adds them to a data structure accessible from outside the program loop scope. This type of infinite loops can sometimes occur due to multithreaded access into a shared unsynchronized data structure. These types of memory leaks manifest as fast growing memory leaks, where if the verbose GC data reports a sharp drop in free heap space in a very short time leads to an OutOfMemoryError.
Friends please add more to this post... dying to see more in this post....

Wednesday, October 17, 2007

Shallow Copy and Deep Copy

The java.lang.Object root superclass defines a clone() method that will, assuming the subclass implements the java.lang.Cloneable interface, return a copy of the object. While Java classes are free to override this method to do more complex kinds of cloning, the default behavior of clone() is to return a shallow copy of the object. This means that the values of all of the origical object’s fields are copied to the fields of the new object.

A property of shallow copies is that fields that refer to other objects will point to the same objects in both the original and the clone. For fields that contain primitive or immutable values (int, String, float, etc…), there is little chance of this causing problems. For mutable objects, however, cloning can lead to unexpected results. Figure 1 shows an example.


--------------------------------------------------------------------------------
import java.util.Vector;
public class Example1 {
public static void main(String[] args) {
// Make a Vector
Vector original = new Vector();
// Make a StringBuffer and add it to the Vector
StringBuffer text = new StringBuffer(”The quick brown fox”);
original.addElement(text);
// Clone the vector and print out the contents
Vector clone = (Vector) original.clone();
System.out.println(”A. After cloning”);
printVectorContents(original, “original”);
printVectorContents(clone, “clone”);
System.out.println(“——————————————————–”);
System.out.println();
// Add another object (an Integer) to the clone and
// print out the contents
clone.addElement(new Integer(5));
System.out.println(”B. After adding an Integer to the clone”);
printVectorContents(original, “original”);
printVectorContents(clone, “clone”);
System.out.println(“——————————————————–”);
System.out.println();
// Change the StringBuffer contents
text.append(” jumps over the lazy dog.”);
System.out.println(”C. After modifying one of original’s elements”);
printVectorContents(original, “original”);
printVectorContents(clone, “clone”);
System.out.println(“——————————————————–”);
System.out.println();
}

public static void printVectorContents(Vector v, String name) {
System.out.println(” Contents of \”" + name + “\”:”);
// For each element in the vector, print out the index, the
// class of the element, and the element itself
 for (int i = 0; i < v.size(); i++) {
  Object element = v.elementAt(i);
  System.out.println(” ” + i + ”(” +element.getClass().getName()+ “):” +element);
 }
System.out.println();
}
}
--------------------------------------------------------------------------------


Figure 1. Modifying Vector contents after cloning
In this example we create a Vector and add a StringBuffer to it. Note that StringBuffer (unlike, for example, String is mutable — it’s contents can be changed after creation. Figure 2 shows the output of the example in Figure 1.


--------------------------------------------------------------------------------


> java Example1
A. After cloning

Contents of “original”:

0 (java.lang.StringBuffer): The quick brown fox
Contents of “clone”:

0 (java.lang.StringBuffer): The quick brown fox
——————————————————–


B. After adding an Integer to the clone

Contents of “original”:

0 (java.lang.StringBuffer): The quick brown fox
Contents of “clone”:

0 (java.lang.StringBuffer): The quick brown fox

1 (java.lang.Integer): 5
——————————————————–


C. After modifying one of original’s elements

Contents of “original”:

0 (java.lang.StringBuffer): The quick brown fox jumps over the lazy dog.
Contents of “clone”:

0 (java.lang.StringBuffer): The quick brown fox jumps over the lazy dog.

1 (java.lang.Integer): 5
——————————————————–

--------------------------------------------------------------------------------


Figure 2. Output from the example code in Figure 1
In the first block of output (”A”), we see that the clone operation was successful: The original vector and the clone have the same size (1), content types, and values. The second block of output (”B”) shows that the original vector and its clone are distinct objects. If we add another element to the clone, it only appears in the clone, and not in the original. The third block of output (”C”) is, however, a little trickier. Modifying the StringBuffer that was added to the original vector has changed the value of the first element of both the original vector and its clone. The explanation for this lies in the fact that clone made a shallow copy of the vector, so both vectors now point to the exact same StringBuffer instance.

This is, of course, sometimes exactly the behavior that you need. In other cases, however, it can lead to frustrating and inexplicable errors, as the state of an object seems to change “behind your back”.

The solution to this problem is to make a deep copy of the object. A deep copy makes a distinct copy of each of the object’s fields, recursing through the entire graph of other objects referenced by the object being copied. The Java API provides no deep-copy equivalent to Object.clone(). One solution is to simply implement your own custom method (e.g., deepCopy()) that returns a deep copy of an instance of one of your classes. This may be the best solution if you need a complex mixture of deep and shallow copies for different fields, but has a few significant drawbacks:





A common solution to the deep copy problem is to use Java Object Serialization (JOS). The idea is simple: Write the object to an array using JOS’s ObjectOutputStream and then use ObjectInputStream to reconsistute a copy of the object. The result will be a completely distinct object, with completely distinct referenced objects. JOS takes care of all of the details: superclass fields, following object graphs, and handling repeated references to the same object within the graph. Figure 3 shows a first draft of a utility class that uses JOS for making deep copies.


--------------------------------------------------------------------------------


import java.io.IOException;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;


public class MyDeepCopy {
/**
* Returns a copy of the object, or null if the object cannot
* be serialized.
*/

public static Object copy(Object orig) {
Object obj = null;
try {
// Write the object out to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(orig);
out.flush();
out.close();
// Make an input stream from the byte array and read
// a copy of the object back in.
ObjectInputStream in = new ObjectInputStream(
new ByteArrayInputStream(bos.toByteArray()));
obj = in.readObject();
}
catch(IOException e) {
e.printStackTrace();
}
catch(ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
return obj;
}
}




Figure 3. Using Java Object Serialization to make a deep copy
Unfortunately, this approach has some problems, too:
It will only work when the object being copied, as well as all of the other objects references directly or indirectly by the object, are serializable. (In other words, they must implement java.io.Serializable.)

Tuesday, October 16, 2007

Java HotSpot VM Options

Java HotSpot VM Options

Standard options recognized by the Java HotSpot VM are described on the Java Application Launcher reference pages for Windows, Solaris and Linux.

Options that begin with -X are non-standard (not guaranteed to be supported on all VM implementations), and are subject to change without notice in subsequent releases of the JDK.

Options that are specified with -XX are not stable and are not recommended for casual use. These options are subject to change without notice.

Some Useful -XX OptionsDefault values are listed for Java SE 6 for Solaris Sparc with -server. Some options may vary per architecture/OS/JVM version. Platforms with a differing default value are listed in the description.

Boolean options are turned on with -XX:+ and turned off with -XX:-.Numeric options are set with -XX:=. Numbers can include 'm' or 'M' for megabytes, 'k' or 'K' for kilobytes, and 'g' or 'G' for gigabytes (for example, 32k is the same as 32768).String options are set with -XX:=, are usually used to specify a file, a path, or a list of commandsFlags marked as manageable are dynamically writeable through the JDK management interface (com.sun.management.HotSpotDiagnosticMXBean API) and also through JConsole. In Monitoring and Managing Java SE 6 Platform Applications, Figure 3 shows an example. The manageable flags can also be set through jinfo -flag.The options below are loosely grouped into three categories.

Behavioral options change the basic behavior of the VM.Performance tuning options are knobs which can be used to tune VM performance.Debugging options generally enable tracing, printing, or output of VM information.
--------------------------------------------------------------------------------
Behavioral Options

Option and Default ValueDescription

-XX:-AllowUserSignalHandlers Do not complain if the application installs signal handlers. (Relevant to Solaris and Linux only.)
-XX:AltStackSize=16384 Alternate signal stack size (in Kbytes). (Relevant to Solaris only, removed from 5.0.)
-XX:-DisableExplicitGC Disable calls to System.gc(), JVM still performs garbage collection when necessary.
-XX:+FailOverToOldVerifier Fail over to old verifier when the new type checker fails. (Introduced in 6.)
-XX:+HandlePromotionFailure The youngest generation collection does not require a guarantee of full promotion of all live objects. (Introduced in 1.4.2 update 11) [5.0 and earlier: false.]-XX:+MaxFDLimit Bump the number of file descriptors to max. (Relevant to Solaris only.)
-XX:PreBlockSpin=10 Spin count variable for use with
-XX:+UseSpinning. Controls the maximum spin iterations allowed before entering operating system thread synchronization code. (Introduced in 1.4.2.)
-XX:-RelaxAccessControlCheck Relax the access control checks in the verifier. (Introduced in 6.)
-XX:+ScavengeBeforeFullGC Do young generation GC prior to a full GC. (Introduced in 1.4.1.)
-XX:+UseAltSigs Use alternate signals instead of SIGUSR1 and SIGUSR2 for VM internal signals. (Introduced in 1.3.1 update 9, 1.4.1. Relevant to Solaris only.)
-XX:+UseBoundThreads Bind user level threads to kernel threads. (Relevant to Solaris only.)
-XX:-UseConcMarkSweepGC Use concurrent mark-sweep collection for the old generation. (Introduced in 1.4.1)
-XX:+UseGCOverheadLimit Use a policy that limits the proportion of the VM's time that is spent in GC before an OutOfMemory error is thrown. (Introduced in 6.)
-XX:+UseLWPSynchronization Use LWP-based instead of thread based synchronization. (Introduced in 1.4.0. Relevant to Solaris only.)
-XX:-UseParallelGC Use parallel garbage collection for scavenges. (Introduced in 1.4.1)
-XX:-UseParallelOldGC Use parallel garbage collection for the full collections. Enabling this option automatically sets
-XX:+UseParallelGC. (Introduced in 5.0 update 6.)
-XX:-UseSerialGC Use serial garbage collection. (Introduced in 5.0.)
-XX:-UseSpinning Enable naive spinning on Java monitor before entering operating system thread synchronizaton code. (Relevant to 1.4.2 and 5.0 only.) [1.4.2, multi-processor Windows platforms: true]
-XX:+UseTLAB Use thread-local object allocation (Introduced in 1.4.0, known as UseTLE prior to that.) [1.4.2 and earlier, x86 or with -client: false]
-XX:+UseSplitVerifier Use the new type checker with StackMapTable attributes. (Introduced in 5.0.)[5.0: false]
-XX:+UseThreadPriorities Use native thread priorities.
-XX:+UseVMInterruptibleIO Thread interrupt before or with EINTR for I/O operations results in OS_INTRPT. (Introduced in 6. Relevant to Solaris only.)
-------------------------------------------------------------------------------
Performance Options

Option and Default ValueDescription

-XX:+AggressiveOpts Turn on point performance compiler optimizations that are expected to be default in upcoming releases. (Introduced in 5.0 update 6.)
-XX:CompileThreshold=10000 Number of method invocations/branches before compiling [-client: 1,500]
-XX:LargePageSizeInBytes=4m Sets the large page size used for the Java heap. (Introduced in 1.4.0 update 1.) [amd64: 2m.]
-XX:MaxHeapFreeRatio=70 Maximum percentage of heap free after GC to avoid shrinking.
-XX:MaxNewSize=size Maximum size of new generation (in bytes). Since 1.4, MaxNewSize is computed as a function of NewRatio. [1.3.1 Sparc: 32m; 1.3.1 x86: 2.5m.]
-XX:MaxPermSize=64m Size of the Permanent Generation. [5.0 and newer: 64 bit VMs are scaled 30% larger; 1.4 amd64: 96m; 1.3.1 -client: 32m.]
-XX:MinHeapFreeRatio=40 Minimum percentage of heap free after GC to avoid expansion.-XX:NewRatio=2 Ratio of new/old generation sizes. [Sparc -client: 8; x86 -server: 8; x86 -client: 12.]-client: 4 (1.3) 8 (1.3.1+), x86: 12]
-XX:NewSize=2.125m Default size of new generation (in bytes) [5.0 and newer: 64 bit VMs are scaled 30% larger; x86: 1m; x86, 5.0 and older: 640k]
-XX:ReservedCodeCacheSize=32m Reserved code cache size (in bytes) - maximum code cache size. [Solaris 64-bit, amd64, and -server x86: 48m; in 1.5.0_06 and earlier, Solaris 64-bit and and64: 1024m.]
-XX:SurvivorRatio=8 Ratio of eden/survivor space size [Solaris amd64: 6; Sparc in 1.3.1: 25; other Solaris platforms in 5.0 and earlier: 32]
-XX:TargetSurvivorRatio=50 Desired percentage of survivor space used after scavenge.
-XX:ThreadStackSize=512 Thread Stack Size (in Kbytes). (0 means use default stack size) [Sparc: 512; Solaris x86: 320 (was 256 prior in 5.0 and earlier); Sparc 64 bit: 1024; Linux amd64: 1024 (was 0 in 5.0 and earlier); all others 0.]
-XX:+UseBiasedLocking Enable biased locking. For more details, see this tuning example. (Introduced in 5.0 update 6.) [5.0: false]
-XX:+UseFastAccessorMethods Use optimized versions of GetField.
-XX:-UseISM Use Intimate Shared Memory. [Not accepted for non-Solaris platforms.] For details, see Intimate Shared Memory.
-XX:+UseLargePages Use large page memory. (Introduced in 5.0 update 5.) For details, see Java Support for Large Memory Pages.
-XX:+UseMPSS Use Multiple Page Size Support w/4mb pages for the heap. Do not use with ISM as this replaces the need for ISM. (Introduced in 1.4.0 update 1, Relevant to Solaris 9 and newer.) [1.4.1 and earlier: false]
--------------------------------------------------------------------------------
Debugging Options

Option and Default ValueDescription
-XX:-CITime Prints time spent in JIT Compiler. (Introduced in 1.4.0.)
-XX:ErrorFile=./hs_err_pid.log If an error occurs, save the error data to this file. (Introduced in 6.)
-XX:-ExtendedDTraceProbes Enable performance-impacting dtrace probes. (Introduced in 6. Relevant to Solaris only.)
-XX:HeapDumpPath=./java_pid.hprof Path to directory or filename for heap dump. Manageable. (Introduced in 1.4.2 update 12, 5.0 update 7.)
-XX:-HeapDumpOnOutOfMemoryError Dump heap to file when java.lang.OutOfMemoryError is thrown. Manageable. (Introduced in 1.4.2 update 12, 5.0 update 7.)
-XX:OnError=";" Run user-defined commands on fatal error. (Introduced in 1.4.2 update 9.)
-XX:OnOutOfMemoryError=";" Run user-defined commands when an OutOfMemoryError is first thrown. (Introduced in 1.4.2 update 12, 6)
-XX:-PrintClassHistogram Print a histogram of class instances on Ctrl-Break. Manageable. (Introduced in 1.4.2.) The jmap -histo command provides equivalent functionality.
-XX:-PrintConcurrentLocks Print java.util.concurrent locks in Ctrl-Break thread dump. Manageable. (Introduced in 6.) The jstack -l command provides equivalent functionality.
-XX:-PrintCommandLineFlags Print flags that appeared on the command line. (Introduced in 5.0.)
-XX:-PrintCompilation Print message when a method is compiled.
-XX:-PrintGC Print messages at garbage collection. Manageable.
-XX:-PrintGCDetails Print more details at garbage collection. Manageable. (Introduced in 1.4.0.)
-XX:-PrintGCTimeStamps Print timestamps at garbage collection. Manageable (Introduced in 1.4.0.)
-XX:-PrintTenuringDistribution Print tenuring age information.-XX:-TraceClassLoading Trace loading of classes.
-XX:-TraceClassLoadingPreorder Trace all classes loaded in order referenced (not loaded). (Introduced in 1.4.2.)
-XX:-TraceClassResolution Trace constant pool resolutions. (Introduced in 1.4.2.)
-XX:-TraceClassUnloading Trace unloading of classes.
-XX:-TraceLoaderConstraints Trace recording of loader constraints.

Heroku Custom Trust Store for SSL Handshake

  Working with Heroku for deploying apps (java, nodejs, etc..) is made very easy but while integrating one of the service ho...