Tuesday, November 27, 2012

JSP (EL Implicit Objects)

  Identifier               Description

 pageContext          PageContext instance
 pageScope             Map-associates name and values of page-scoped attributes
 requestScope         Map-associates name and values of request-scoped attributes
 sessionScope         Map-associates name and values of session-scoped attributes
 applicationScope    Map-associates name and values of application-scoped attributes  parameters
 param                   Map-stores the primary values of the request parameters by name
 paramValues          Map-stores all values of the request parameters as String arrays
 header                  Map-stores the primary values of the request headers by name
 headerValues         Map-stores all values of the request headers as String arrays
 cookie                   Map-stores the cookies accompanying the request by name
 initParam              Map-stores the context initialization params of the appln by name

Wednesday, November 7, 2012

Java Tidbits .......................... ( Riding over Methods )

Method Overriding is form of Polymorphism . Since which method to be called will be  resolved at runtime  by the  object assigned to reference.

Rules for overriding are :

  • A method if overridden in subclass should have same argument.
  • same or  extended return type(Covariant)
  • arguments can be declared as final additionally in subclass provided the datatype is same .
  • can throw checked exception if base class method too throws the checked exception .
  • the exception thrown can be  either same or subclass of  thrown exception in base method.
  • // Rule hold only for checked exception 
  • Access modifiers can make it less restrictive, but not more restrictive.
Field Hiding
A subclass cannot override fields of the superclass, but it can hide them by declaring  with same name .
if  want to access  base class's field then  user super to invoke  field .

While implementing interfaces all above rules are applicable for overriding interface declared methods too.
Exception and return of covariant types are applicable .

Can a private method be overridden by a subclass?
NO! Since the subclass,  cannot inherit a private method, it therefore cannot override the method—overriding depends on inheritance.

Wednesday, October 17, 2012

Java Tidbits ....................... reading streams from File

1) FileReader fop = new FileReader(f);   // file or string
int n =0;
       
  while ((n=fop.read())!=-1)     // read a single character from file
      System.out.print((char )n);
in above  code  we can use read(byte[]) too .
in that case it will read the data from file and  populate in a defined  byte array that can be printed / used later  in next example done like that .


2) FileInputStream fis = new FileInputStream(f);  // file or string
byte b[] = new byte[1048];
System.out.println(fis.read(b));

3)  InputStream can be piped to InputStreamReader

     InputStreamReader reader = new InputStreamReader(fis);    // inputstream

4) Any reader instance can be piped to BufferedReader .

   BufferedReader bufferedReader = new BufferedReader(fop);  // Reader instance is required
    BufferedReader bufferedReader = new BufferedReader(reader);// allowed instance of reader

we can readLine from BufferedReader.

Java Tidbits ...................wrinting streams to file

The other low level ways to write  bytes into File rather than chars  requires the use of stream classes.
Like reading image data and writing into file . 

Hierarchy of stream classes is published on previous post.

To write byte or character stream into File we need  instance of OutputStream 
ie: ObjectOutputStream or FilterOutputStream  or FileOutputStream

OutputStreamWriter opts = new OutputStreamWriter( OutputStream opt); 

1) FileOutputStream fops = new FileOutputStream(f, true);
    OutputStreamWriter opts = new OutputStreamWriter(fops);   // fops instanceof OutputStream
        opts.write(97);
        opts.close();


public BufferedOutputStream(OutputStream out , in size)  // size is optional
2) BufferedOutputStream bf = new BufferedOutputStream(fops);
        bf.write(66);
        bf.close();


3) Pipe any instance of Outputstream to DataOutputStream       bf or fops both qualifies
        DataOutputStream df = new DataOutputStream(bf);   // from (2) bf instance of OutputStream
        df.write(67);
        df.close();

flexibility given in DataOutputStream is its instace can write  double , int , boolean float etc too the writer .
        df.writeBoolean(new Boolean(true));
        df.writeDouble(34.12);

4) use of PrintStream with file as argument will override the whole file.
     PrintStream pf = new PrintStream(f); // override file
        pf.write(68);
        pf.close();


piping it to any outputstream will prevent it from overriding .

5) PrintStream pf = new PrintStream(fos,true);
        pf.write("hello");
        pf.close();

It has very specific methods for writing , formatting , printing text into file.
6)
   BufferedWriter bw= new BufferedReader(fow);  // Writer
   we can wrap printwrite into bufferwriter  and reverse too
   BufferedWriter bw = new BufferedWriter(pos);  // allowed
   PrintWriter pos = new PrintWriter(bw);  // allowed


   we can write a new line character by using bufferwriter .

Java Tidbits .................... (File Streams heirarchy)




















In the above picture  , all classes that implements DataInput / DataOut interfaces provide the facility to  read / write  byte streams into the File .

Java Tidbits ..........................(File I/O)

File f = new File(string str)

f is an instance of File object . It wont  create or delete any file  with the name  str on DISK.
it can be checked to see if there is any such file with the path name specified by str or not .
f.createNewFile() will craete the file in specified path  throws IOException
f.mkDir() is for making directories

To write into file FileWriter object is required
 FileWriter fow = new FileWriter(file instance , boolean  append );
new FileWriter(file instance );  // by default append  is false  & it will overwrite the file./string
FileWriter fow = new FileWriter(f,true);  // append at last 

FileOutputStream fops = new FileOutputStream(file ) // file or string
FileOutputStream fops = new FileOutputStream(f, append);

ways to write into file 

1) FileWriter fow fow = new FileWriter(f,true);       
       
        fow.append("Hello ");   
        fow.append("\nHow r u ?");
        fow.flush();
        fow.close();

//Note : FileWriter extends FileOutPutStream

2) FileOutputStream fops = new FileOutputStream(f, true);
        fops.write("My name is khan".getBytes());
        fops.flush();
        fops.close();

3) PrintWriter pos = new PrintWriter(file); // or string
        pos.write("Ayyaiyya!");       
        pos.flush();
        pos.close();

4) FileOutPutStream can be  piped to PrintWriter .
PrintWriter pos = new PrintWriter(fops, true); // autoFlush true
        pos.write("Ayyaiyya!");       
        pos.flush();
        pos.close();


5) FileWriter can be  piped to PrintWriter .
PrintWriter pos = new PrintWriter(fow, true); // autoFlush true
        pos.write("Ayyaiyya!");       
        pos.flush();
        pos.close(); 


6)Pipe OutputStreamWriter to PrintWriter 
OutputStreamWriter opts = new OutputStreamWriter(fops);
        PrintWriter pos = new PrintWriter(opts, true);
        pos.write("Great!");

        pos.flush();
        pos.close();

Tuesday, October 16, 2012

Java Tidbits ............................(Initializers!)

A class has  instance vars and instance methods , constructors  and  init block and static init block.
The order of initializer block to be called is 
  1. declaration of  vars ( both static as well as non -static)
  2. static block
  3. init block
  4. constructor

declaration-before-reading Rule
declaration of a field must occur before its usage in any initializer
expression if the field is used on the RHS of an assignment in the initializer expression.
declaration-before-reading rule: it does not apply if the
initializer expression defines an anonymous class, as the usage then occurs in a different class which has its own accessibility rules in the enclosing context.
final static fields can only be initialized either at time of declaration or with in static block.


Here is an example 


public class MyInitializer {
   
     boolean flag = true;
     final static int ROOM=7;
     int l=h=8; // declaration-before-reading
     int f=  new mysmall(){
                 int getsmall( ){return h;}
                 }.getsmall();
     //mytest.BOOK;
     int k = getK(); 
   
     int  getK(){
        return h; // declaration-before-reading
     }

   
     static{
         NUM=200; // declaration-before-reading
        // ROOM=45;
         System.out.println("static init block "+ROOM);
     }
     {
         System.out.println(" instance init block ");

         try{
         if(flag )
             throw new Exception();
         }catch(Exception e){System.out.println(" caught in init block"+ROOM);}
     }
     int h=9;
   
     MyInitializer(){
           
         System.out.println(" A constructor will be called in end "+ROOM);
     }
     private static int NUM;
   
     interface mytest { int BOOK=60;}
     class mysmall{ int getsmall( ){return 20;} }

    public static void main(String args[]){
        MyInitializer mObj = new MyInitializer();
        System.out.println(" mObj.f="+ mObj.f + " mObj. k="+mObj.k + " NUM"+NUM);
        // both k & f will be 0 since h is not initialized .
        // if h is initialized  before then it will take its value
        // here its picking 8  since h 's value is overwritten
    }
}

Tuesday, October 9, 2012

Java Tidbits......................(Polymorphism)

This is the topic that had shown me stars during day ! Every time when i read any java book i felt that i am pretty clear with this & can handle  any type of Qs but every time i failed .

polymorphism  is simple concept of deciding  at run time which object's method to be called .
Here i will paste few examples where i was most confused

case 1

class ABC {
           private int a=10;
           int getA ( )
            {return a;}
}

class BCD extends ABC{
            private int a=20;
            int getA ( )
            {return 2*a;}
}

public static void main(Strings args[])
{

ABC a = new ABC();
s.o.p ( a.getA( ) )  ;  
BCD b = new BCD();
s.o.p ( b.getA( ) ) ;

//   b=a;                  Compiler Error

b = ( BCD ) a;            //  Need to type cast explicitly
s.o.p ( b.getA( ) ) ;      // ClassCastException at run time


}

Reason 1

Compiler will error because upcasting is not automatic in java
ClassCastException will come when the object reference of base class point to base class object .

to remove that
a = new BCD ( ) ;
b= ( BCD ) a;

....to be continued ....





Ramblings of a confused Java programmer

javac -d path_to_classes_dir name of java file

The -cp option can be used to set the class path for each application individually

for example
-cp /pgjc/work:/top/bin/pkg:.
Here  path-separator character ':' for Unix platforms to separate the entries, and also included the current directory (.) as an entry.
For windows it is ';' used as path separator

One cannot call method of base class using super keyword from static method.
Given below is example
   class SuperCalc {
                 protected static  int multiply(int a, int b) { return a * b;}
    }
    class SubCalc extends SuperCalc{
                 public  static  int multiply(int a, int b) {
                 int c =super.multiply(a, b);   // wrong !! cannot use super from inside static
                 return c;
     }
 }

Class names and method names exist in different namespaces.


Collections.sort() // can only be used for List or its subclasses
Arrays.sort() // can only be used for object arrays or long[]

Default modifier is narrower than protected modifier . Method having default access modifier can be declared as protected in its  sub class.
Default member  accessibility is more restrictive than protected member accessibility.

A base class reference cannot be assigned to sub class reference . ( it will give compile time error ) if
type casted then will give runtime class cast exception.
but a subclass ref can be assigned to base class ref

Need to go through Locale / Date / Date format / Localization


An anonymous inner class can extend either one subclass or implement one
interface. Unlike non-anonymous classes (inner or otherwise), an anonymous
inner class cannot do both. In other words, it cannot both extend a class and
implement an interface, nor can it implement more than one interface.

this is not only a keyword its a constructor !

class Base1{
               private int  score;
               private int goal;
   
              Base1()
              {
                 this(20);   
              }
              Base1(int score)
              {
               //this.score=score;   valid
               this(score, 2*score);
              }
              Base1(int score, int goal)
              {
               this.score=score;
               this.goal=goal;
               }
               void printScore()
              {
                 System.out.println(" Score ="+score + "goal = "+goal);
              }
}

addAll() , retainAll(), removeAll () are destructive operations .!! be safe while playing .

Generic Type classes cann't be instantiated !
nor Arrays can be formed of Generic Type .




The && and || operators are short circuit operators. A short circuit operator is one that doesn't
necessarily evaluate all of its operands. Take, for example, the operator &&. What happens when Java
executes the following code?
if (0 == 1 && 2 + 2 == 4) {
out.println("This line won't be printed.");
}


Realize that the condition (2 + 2 == 4 || whatever) must be true, no matter what
the whatever condition happens to be.



Field of an object is accessed using a reference, it is the type of the reference, not the class of the
current object denoted by the reference at runtime  .  It is called Field Hiding .

Interfaces are by default static , irrespective of their declaration.
Non static Inner classes can't have static  members/ interfaces / static  methods .
Only inner classes can be declared as static  .

Interfaces cannot be static unless they are inside a class.

Monday, October 8, 2012

Java Tidbits .................(Perm Space)

Permanent Generation Space in JVM is a separate memory area than usual heap / stack .
It contains the information about static classes , variables etc that are stored permanently ..like Class's definitions are stored on it permanently . Class loaders deploy and undeploy classes all the time.When an application is deployed or undeployed, its class definitions and Classloader are respectively put into and removed from the permanent generation heap. 
When this space in memory gets filled  then program throws  OutOfMemoryError: PermGen Space error.
More information for this are at 


To make size of the permanent generation heap space bigger

-XX:MaxPermSize=256m is the cmd

Friday, October 5, 2012

Overriding start() ?...........gotcha !!

I tried overriding start() , even though its not required since extending  thread means one can override run() that will be sufficient to do desired work . But again showing my stupidity i did that as below 


public class MyThread extends Thread{   
   
    public void start()
    {       
        System.out.println( " MyThread started " );
        run();
    }
    public void run(){
       
        for(int i =0 ; i < 3 ; i + + )


            System.out.println( i );


             throw new RuntimeException();
    }
   
    public static void main(String...a)

  {
        MyThread mt =  new MyThread();
        mt.start();
        System.out.println ( " Done " );
    }

}


And it made me puzzled that while running this program it executed in single threaded environment .
did you get the cause ? 
because in order to spawn a new thread start() method must call super.start() from with in start() that internally invokes run() method of custom thread .Other wise it would have been a regular method call .

So i need to over start as below & no need to call run() explicitly

public void start(String... args)
    {
       
        System.out.println ( " MyThread started " );
        super.start();
    }


Next Time respect Thread little more ! :-)

Wednesday, October 3, 2012

Java Tidbits ....................5(Covariant)

  •  An overriding method, should define exactly same set of argument list, as the overridden method, or else we will end up defining an overloaded method. This includes the covariant data types, i.e., if any argument in the overriding method is a subclass of the argument defined in the super class, we will end up defining an overloaded method.
  •  A valid overriding method can define a return type, which is a subclass of the return type defined by the Overridden method in the super class. 
Run this example  and tweak your brain.
---------------------------------------------------------------------------------
class TestB{
    int kk=9;
    public  Object mytest(Object o)
    {
        System.out.println("ok in Base");
        return o;
    }
}

public class TestA extends TestB{
   
    int kk =8;
   
    public  String mytest(Object o )
    {
        System.out.println("ok in overloaded sub class");
        return o.toString();

    }
    public  void mytest(String o )
    {
        System.out.println("ok in sub class");

    }
    public static void main(String args[])
    {
      
        TestB tb = new TestB();
        TestA ta = new TestA();

        
        ta.mytest("ok");
        tb.mytest("ok");
        System.out.println(" ta.kk = "+ ta.kk + "tb.kk = "+tb.kk);
      
        tb = new TestA();
        tb.mytest("ok");
        System.out.println("tb.kk = "+tb.kk);

      
        System.exit(0);

     }

For more examples on covariant types refer >>
http://cafe4java.com/mockexams/scjp/mock1/q1.php

Monday, October 1, 2012

Java Tidbits ............................4(enum)

  • Enums are special classes whose fields are constants.
  • Enum can be declared either inside of a class or as separate class.
  • When outside a class Enum can either be public or default access modifier. By default nested enum are static ( ie inside class ).
  • In Enum definitions the enum constants must be declared before any other declarations in an enum type. ( compile error will be thrown if it is occurs )
  • Enum cannot be declared inside methods .why ? ( because methods cannot have class ) 
  • ; colon is optional to be placed at end of enum syntax.
  • Enum cannot be invoked via new operator .
  • Like classes Enum can have multiple argument constructor or may have overloaded constructors  .
  • Like classes Enum can have methods definitions.
  • Enum can  provide constant specific class body ie : a particular constant can override one or more  of its methods .
  • Enum are implicitly Serialiazable and comparable and extends Enum abstract class , so enum can be  serialized and can be put into  ordered collection.
  • If there is any abstract method declared inside enum class then each of its enum type must have to provide its definition.
  • Abstract & Final Enum cannot be defined.
  • equals(), compareTo(), finalize() methods are final . it cannot be overridden.
  • Enum can implement interfaces but cannot extends any other class. 
  • Enum cannot be of Generic Type.
Practice few Enum from K & B book .

http://www.ejavaguru.com/scjp5freemockexam.php#enumq9

Generics aren't so generic !

Generics in Java 5 enables Types(class/interface) to  have parameters when defining classes, interfaces and methods.A generic type is a type with formal type parameters. While A parameterized type is an instantiation of a generic type with actual type arguments.

A generic type is a reference type that has one or more type parameters. These type parameters are later replaced by type arguments when the generic type is instantiated (or declared )

If the compiler erases all type parameters at compile time, why should you use generics?

1) To provide compile time casting.
2) Elimination of casts
3) Enabling programmers to implement generic algorithms. ..( more later )

******UpperBound WildCards
ex:
List <  ? extends Number >

take method
public static double sumOfList(List < ? extends Number > list) {
    double s = 0.0;
    for (Number n : list)
        s += n.doubleValue();
    return s;
}


here both
List < Integer >  li = Arrays.asList(1, 2, 3);
List < Double > li = Arrays.asList(1.1, 2.1, 3.1); 
can substitute at compile time.


******LowerBound WildCards 


public static void addNumbers(List < ? super Integer > list) {
    for (int i = 1; i <= 10; i++) {
        list.add(i);
    }
}
 
Here only  
List < Integer > li = Arrays.asList(1, 2, 3);
or List < Number > li = Arrays.asList(1, 2, 3); 
can be passed at compile time.
Since Integer or any of its super class is allowed .

More explanation on Generic Types is given at

http://www.angelikalanger.com/GenericsFAQ/FAQSections/ParameterizedTypes.html

Friday, September 28, 2012

Java Tidbits ........................3 (Serialization)

  • A class that needs to be serialized must implement  marker interface Serializable.
  • A class can extends a base class that doesn't implement Serializable .
  • A class if  contains or has-a relation with any of such  instance variable that doesn't implement Serializable will throw runtime exception while serializing . [ ..java.io.NotSerializableException ..]
  • If the base class doesn't implement Ser then in that case  while deserializing object the constructor of base class is called again while the transient and static variables of object will be intialized to default and recent vale respectively .
Try running below example 

import java.io.*;

class Player {
Player() { System.out.print("p"); }
}
public class CardPlayer  extends Player implements Serializable{
// Player p =new Player (); this can be commented to check Has-A relation ship 
CardPlayer() { System.out.print("c"); }
public static void main(String[] args) {
    CardPlayer c1 = new CardPlayer();
try {
             FileOutputStream fos = new FileOutputStream("play.txt");
             ObjectOutputStream os = new ObjectOutputStream(fos);
             os.writeObject(c1);
             os.close();
            FileInputStream fis = new FileInputStream("play.txt");
            ObjectInputStream is = new ObjectInputStream(fis);
            CardPlayer c2 = (CardPlayer) is.readObject();
            is.close();
} catch (Exception x ) { System.out.println("here ") ; x.printStackTrace();}
}
}

Thursday, September 27, 2012

Java Tidbits ............................2 (Finally)


will finally execute when return / System.exit(0) is invoked in try or catch block?

Yes . with return finally block will execute before returning the value but with System.exit(0) it immediately quits JVM so no point of execution any furthur 

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

BEWARE , Finally is not guaranteed to complete ! It all depends on user's implementation.
see below example ::


public class OverAndOver {
 static String s = "";
 public static void main(String[] args) {
 try {
 s += "1";
     throw new Exception();
   } catch (Exception e) { s += "2";
     } finally { s += "3"; doStuff(); s += "4";
     }
 System.out.println(s);
 }
 static void doStuff() { int x = 0; int y = 7/x; }
 }


Wednesday, September 26, 2012

Java Tidbits ............................1

Can one extends multiple interfaces in java ?


interface A {

void doStuffA();
}

interface B {

void doStuffB();
}

interface C extends A,B  {
void doStuffC();
}

// Is C valid interface ?
Yes ! it is because interfaces are not classes ....... 

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


Monday, September 3, 2012

To Extend or to Implement

This is the most basic question that i never been able to understand until i made a program in which i started a  thread twice .

The answer that novice programmer give is
1) a Java class can have only one superclass. So if your thread class extends java.lang.Thread, it cannot inherit from any other classes. This limits how you can reuse your application logic.

correct !!
Now when same question is asked to an exp programmer then some more reason is expected  .
The reason is

2) Once a thread is  finished with its task ie: comes out of run method and cannot be restarted . Thread instance is subjected to garbage collection. So in order to resubmit the task again at some point then implementing interface is required. Also  the task can be submitted for a later point of execution .


From a design point of view, there should be a clean separation between how a task is identified and defined, between how it is executed. The former is the responsibility of a Runnable impl, and the latter is job of the Thread class.

Wednesday, August 29, 2012

To wait() or to sleep()

The concept of wait and sleep in java threading i couldn't get easily . I read at several tech blogs  and docs that wait should be called by object  while sleep is called by thread . Both methods are used to pause a running thread momentarily . However, i couldn't understand for a long , what does that mean by calling a object ? If wait is to be called  by object then why Thread.currentthread.wait () is visible ? because an object can be of a thread also . 
The thing is a Thread when wants to wait . it should hold an object & use that object to wait  or either it can directly call Thread.sleep(). In Former case object  should be either notify or  be provided  few millisecs to wait . sleep() can be preferred to call when  thread has to wait for small fraction of time .

Both wait() and sleep() cause the current thread to pause execution, not the thread on which you you call them. There is no way to cause a different thread to pause. 

If wait is being  called on a thread then it would give IllegalMonitorStateException .

Tuesday, July 17, 2012

volatile ..java

Use of volatile keyword makes sense when there is a shared object that is being accessed  / modified by multiple threads .Using volatile keyword ensures that variable is never kept in register (stack) for a thread . It will always be read from main memory .
A thread  will never cache the value of a volatile declared variable in its stack space  . so when another thread or by same thread any modification occurs on the volatile variable . its immediately reflected .
However i have not found any running example to show the volatile  affect clearly .

Tuesday, June 26, 2012

WSDL ( in brief )

WSDL is platform- and language-independent and is used primarily to describe SOAP services. It represents the definition of web services . Through  a published WSDL user can create the appropriate soap request to access the publicly available  web service methods. WSDL is written in XML and has 6 major elements .


  • definitions -- root Element
  • types -- data types of all parameters passed to a web method
  • message -- name of the web method that needs to be called or sent in response . its one way only.
  • portType -- it combines multiple messages to form a complete one-way or round-trip operation.
  • binding -- A binding defines message format and protocol details for operations and messages defined by a particular portType.
  • service -- The service element defines the address for invoking the specified service. Most commonly, this includes a URL for invoking the SOAP service.

a sample wsdl can be  seen at below URL
http://www.gotoworkspace.com/us/soap3/timeClockSetupServer.php?wsdl

its respective  soap request for operation (method) named updateTransferJobStatus will be as

< s11:Envelope xmlns:s11='http://schemas.xmlsoap.org/soap/envelope/' >
  < s11:Body >
    < ns1:updateTransferJobStatus xmlns:ns1='urn:gotoworkspaceTimeClock' >
      < clientconfig  /> 

    < tableRowID />
   < recordDetails /> 
  < / ns1:updateTransferJobStatus >
 < / s11:Body >
< / s11:Envelope >
 

and for  operation getPendingJobs corresponding soap request will be 


< s11:Envelope xmlns:s11='http://schemas.xmlsoap.org/soap/envelope/' >

     < s11:Body >
< ns1:getPendingJobs xmlns:ns1='urn:gotoworkspaceTimeClock'>
      < clientconfig />    

  < / ns1:getPendingJobs >  
 < / s11:Body >
< / s11:Envelope >
 

Sunday, April 29, 2012

JVM heap size [ missed concepts ]

This is regarding the  concept of JVM heap size when running on  machines having larger  RAM .The primary advantage of running Java in a 64-bit environment is the larger address space. This allows for a larger Java heap size and an increased maximum number of Java Threads. It's important to note that 64-bit implementation doesn't mean that that built-in Java types (such as integers) are doubled in size from 32 to 64.

However, addressing larger amounts of memory come with a small performance loss in 64-bit VMs (compared to a 32-bit VM) because every reference takes 8 bytes instead of 4.
Loading these extra 4 bytes per reference impacts the memory usage, which causes slightly slower execution (depending on how many pointers get loaded during the Java program's execution).

64-bit Java implementation enables to create and use more Java objects, thus breaking the 1.5-1.6 GB heap limit we have in 32 bit.

below is the command that will set minimum and maximum  heap size for application

java -d64 -Xms2g -Xmx80g MyApp

The above JVM args does not create a process with 80g heap. It only creates a process with 2g of Heap and will only grow till 80g if required and if RAM is available.
by specifying Xmx80g, one is only restricting the maximum heap size that the Java process can use.
When the heap size exceeds the limit specified memory , the behavior of  allocating memory to java process depends on OS.OS can allocate more memory from with in the RAM ( if there is any free space not being used by other user processes or it can allocate memory from disk ) . If heap size size exceeds physical memory then the heap begins swapping to disk which causes Java performance to drastically decrease. It has been observed that after a threshold  memory reaches the performance of application wont  increase considerably by increasing heap size.
For more details on this study click at below link
http://docs.redhat.com/docs/en-US/JBoss_Enterprise_Application_Platform/5/html/Performance_Tuning_Guide/chap-Performance_Tuning_Guide-Java_Virtual_Machine_Tuning.html

The bigger the heap size slower (after a threshold value ) will be performance because it will make GC to be a hazardous task to run.Because the more of time spent on GC. The performance of the application highly depends on how one size the heap generations and GC parameters.

Sun recommends to enable either the Parallel or Concurrent garbage collectors when running with heaps larger than 2 GB.These collectors attempt to minimize the overhead of collection time by either of the following:
-       collecting garbage concurrent with the execution of your Java application
-       utilizing multiple CPUs during collections

Here is good link  providing some info about how to improve performance in multi processor environment.
http://www.jroller.com/imeshev/entry/effect_of_jvm_heap_size

If a web server like jboss is running .it will have its separate heap space than any web application deployed on it .
any webservice deployed and running in it will use its own address space by explicitly giving jvm args to it .

Friday, April 20, 2012

synchronization Do and Do Nots

Its very likely who don't program often multithreading in their code to synchronize on objects that can later  create big trouble. Recently i did some mistakes and so i am writing here lesson learned from  it.
  • Never synchronize such object that can have NULL value ( at some instance of  program ).
  • Never synchronize on string literals . like ( String str="hello" ) here str is string literal not an object.
  • Better to call synchronization over object that never changes its state.
  • Avoid making synchronized methods unless its not required , since that can hold lock form  whole time during its execution.
still learning ....

Thursday, April 12, 2012

MySQL titbits .....................2

Are you annoyed by loud echo sound whenever you type a wrong sql command on cursor?
Just give -b while logging into command prompt .

mysql -b -u root

you will get rid of error prompts.

Tuesday, April 10, 2012

MySQL titbits .....................1


Today my friend asked how to create procedures in MySQL ... i just created this small example to get her a clue.

___________________________

procedure definition.
___________________________


DELIMITER $$
DROP PROCEDURE IF EXISTS myProc$$
CREATE PROCEDURE myProc()
BEGIN
DECLARE myvar char(10);
DECLARE len, ctr int DEFAULT 1;
SELECT count(*) INTO len FROM ss_temp ;

WHILE ctr<=len DO
select ctr;
SELECT name INTO myvar FROM ss_temp WHERE sub_id= ctr;

IF myvar ='songs' THEN
update ss_temp set name='Jokes' where sub_id=ctr;
ELSE
update ss_temp set name='songs' where sub_id=ctr;
END IF;
SET ctr = ctr + 1;
END WHILE;

END$$
DELIMITER ;

__________________________

check if procedure exists

SHOW PROCEDURE STATUS;
________________________

call procedure

call myProc();

_______________________

Tuesday, April 3, 2012

Networking Protocols Categorization

Networking layer divisions

Layer 1 Based on symbols . Physical layer
Layer 2 Based on Frames . Link Layer ARP/OSPF /PPP/ MAC /
Layer 3 Based on Packets . Natework Layer ICMP/IPV6/IGMP/IPSec
Layer 4 Based on Segmanets . Transport Layer TCP/UDP/RSVP/SCTP
Layer 5 Based on Messgaes . Application Layer Protocols SMPP/SMTP/SIP/SNMP/HTTP/FTP/SSH/DHCP/DNS/TELNET
.

All those protocols that send messages are application layer protocols . Like SMPP /SIP that are text based protocols . However the messages are being sent over TCP Layer 4 .

Monday, April 2, 2012

Must known basics in Java

How to print integer value of a char in java?.......................by typecasting data type (int)'a'
what will be output of char ch=296; sysout(ch).......................?
is it valid declaration ? float a=0.7; .........................................No
what will it print ? int i=+-30; or int i=-+30 ............................-30
what will it print int i=10/0; sysout (i); ...................................Airthmatic Exception
what will it print double d=10/0.0; sysout (d); .......................-Infintiy (Double.NEGATIVE_INFINITY)