giovedì 6 settembre 2012

Notes about presentation Performance Tuning by Kirk Pepperdine

In case of performance troubles :
- don't start with code inspection.
- start with Execution profiling instead (may help to find out code bugs)
- add GC debuggin/loggins options or take a look to JMX GCBeans
Correct performance tuning process
1 Set a baseline
2 Modify only one thing a time
3 Make performane test / create new baseline
4 Restart the process again if performance doesnt increase significantly

Basic things to watch at
cpu utilization (don't waste cpu cycles)
application  OS interactions
locks
network io
disk io

Performance monitoring TOOLS TO START with 
System monitoring tools (info about CPU, server Memory used , Network IO, Disk IO
Memory monitoring tools
JVM monitoring tools (garbage collection, memory usage, threads)
Example
Free sample tool visual vm for JMV 
Memory leaks analysis
thread monitoring (starving threads, blocked threads )
thead dump (shows blocked threads and running code )
Different memory areas usage (Survivor space bigger / hidden space)

Resources
java performance tuning by  charlie hunt
http://java.sun.com/performance/reference/whitepapers/tuning.html 

Other Presentations
(Also available in you tube at  http://www.youtube.com/watch?v=nvvPM2OES58 )
http://presentz.org/jugtorino/201010_gc

Mailing list
hotspot-gc-use@openjdk.java.net

mercoledì 5 settembre 2012

VarArgs method samples

/**
 *
 */
package test;
/**
 * @author Paolo
 *
 */
public class VarArgsTest {

 public static void method1VarArgs(int ...intsArray){
  System.out.println("length ="  + intsArray.length);

 }


 public static void method2VarArgs(String ...stringsArray){
  System.out.println("length ="  + stringsArray.length);
 }

 /**
  * @param args
  */
 public static void main(String[] args) {
  method1VarArgs();
  method1VarArgs(1,2,3);
  method2VarArgs();
  method2VarArgs("a", "b");
 
 }
}


And output is :

length =0
length =3
length =0
length =2


NOTES: Arrays  are never null (neither if method is called without any parameter )

sabato 25 agosto 2012

JSF EL different behaviour with boolean vs Boolean Bean attribute

According Java Bean specification when you define a bean attribute (any kind of type - primitive or Object) you should also define getter and setter methods.

For get method a special attribute is the boolean attribute; infact for boolean attribute you may implement both  'is' method and 'get' method.

Sometimes you may choose for some reason to change an attribute from boolean to Boolean type.

You can make your change but with some concerns:

-consider how attribute initialization differs between  primitive boolean (compiler force you to initializate to 'false' or 'true' value) and Boolean (you can leave it null).

- another great difference is about getter methods: infact with Boolean type you have to implement get method and not is method (allowed only for boolean) otherwise you may expect errors.



Here a sample:

HTML JSF page

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html">
   <h:head>
      <title>Welcome</title>
   </h:head>
   <h:body>
      <h:form>
         <h3>Please enter your name and password.</h3>  
         <table>
            <tr>
               <td>Name:</td>
               <td><h:inputText value="#{user.name}" rendered="#{user.illiquid}" /></td>
            </tr>
            <tr>
               <td>Password:</td>
               <td><h:inputSecret value="#{user.password}"/></td>
            </tr>
         </table>
         <p><h:commandButton value="Login" action="welcome"/></p>
      </h:form>
   </h:body>
</html>

 That's is user backing bean with visible property type changed from boolean to Boolean.

package com.corejsf;

import java.io.Serializable;
import javax.inject.Named;
   // or import javax.faces.bean.ManagedBean;
import javax.enterprise.context.SessionScoped;
   // or import javax.faces.bean.SessionScoped;

@Named("user") // or @ManagedBean(name="user")
@SessionScoped
public class UserBean implements Serializable {
   private String name;
   private String password;
   private Boolean visible = true;

   public String getName() { return name; }  
   public void setName(String newValue) { name = newValue; }

   public String getPassword() { return password; }
   public void setPassword(String newValue) { password = newValue; }  
  
   public Boolean isVisible(){
       return visible;
   }
  }

Here the error
/index.xhtml @15,83 rendered="#{user.visible}": The class 'com.corejsf.UserBean$Proxy$_$$_WeldClientProxy' does not have the property 'visible'.

And here fixed bean

package com.corejsf;

import java.io.Serializable;
import javax.inject.Named;
   // or import javax.faces.bean.ManagedBean;
import javax.enterprise.context.SessionScoped;
   // or import javax.faces.bean.SessionScoped;

@Named("user") // or @ManagedBean(name="user")
@SessionScoped
public class UserBean implements Serializable {
   private String name;
   private String password;
   private Boolean visible = true;

   public String getName() { return name; }  
   public void setName(String newValue) { name = newValue; }

   public String getPassword() { return password; }
   public void setPassword(String newValue) { password = newValue; }  
  
   public Boolean getVisible(){
       return visible;
   }
  
  



giovedì 16 agosto 2012

index rebuild oracle crontab - beta

Still BETA


#!/bin/bash
 
##function
check_id_oracle() {
whoami | grep oracle > /dev/null
if [[ "$?" -eq 0 ]]
then
echo "good - you are oracle"
else
echo "you must be oracle"
exit 1
fi
}
 
 
check_be_active() {
ps -ef | grep "[/j]boss-4.2.3GA" > /dev/null
if [[ "$?" -eq 0 ]]
then
echo "good - be active"
else
echo "be stand by"
exit 1
fi
}
 
. .profile
check_id_oracle
check_be_active
v_schema=INEM_REP
sqlplus -s INEM_REP/INEM_REP@XE <<-EOF 2>&1 > /dev/null
set head off
set linesize 60
spool /tmp/rebuild_idx_${v_schema}.sql
select 'spool /tmp/rebuild_idx_${v_schema}.log' from dual;
select 'alter index ' ||INDEX_NAME||' rebuild online;' from user_indexes where TABLE_NAME='ITEMCONFIG' and INDEX_TYPE='NORMAL';
select 'alter index ' ||INDEX_NAME||' rebuild online;' from user_indexes where TABLE_NAME='SINGLE_VALUE_ATTRIBUTE' and INDEX_TYPE='NORMAL';
select 'alter index ' ||INDEX_NAME||' rebuild online;' from user_indexes where TABLE_NAME='STRUCT_VALUE_ATTRIBUTE' and INDEX_TYPE='NORMAL';
select 'alter index ' ||INDEX_NAME||' rebuild online;' from user_indexes where TABLE_NAME='MULTI_VALUE_ATTRIBUTE' and INDEX_TYPE='NORMAL';
select 'alter index ' ||INDEX_NAME||' rebuild online;' from user_indexes where TABLE_NAME='VALUES_MV_ATTRIBUTES' and INDEX_TYPE='NORMAL';
select 'alter index ' ||INDEX_NAME||' rebuild online;' from user_indexes where TABLE_NAME='VALUES_STRUCT_ATTRIBUTES' and INDEX_TYPE='NORMAL';
select 'alter index ' ||INDEX_NAME||' rebuild online;' from user_indexes where TABLE_NAME='NGN_ENTITY_NODE_PROPERTY' and INDEX_TYPE='NORMAL';
select 'alter index ' ||INDEX_NAME||' rebuild online;' from user_indexes where TABLE_NAME='NGN_NODE_INTERFACE' and INDEX_TYPE='NORMAL';
select 'alter index ' ||INDEX_NAME||' rebuild online;' from user_indexes where TABLE_NAME='NGN_NODE_INTERFACE_CREDENTIALS' and INDEX_TYPE='NORMAL';
select 'alter index ' ||INDEX_NAME||' rebuild online;' from user_indexes where TABLE_NAME='L_AGGR_TO_NGN_NODE' and INDEX_TYPE='NORMAL';
select 'alter index ' ||INDEX_NAME||' rebuild online;' from user_indexes where TABLE_NAME='L_AGGR_DOMAINS' and INDEX_TYPE='NORMAL';
select 'alter index ' ||INDEX_NAME||' rebuild online;' from user_indexes where TABLE_NAME='L_AGGR_INTERFACE' and INDEX_TYPE='NORMAL';
select 'alter index ' ||INDEX_NAME||' rebuild online;' from user_indexes where TABLE_NAME='L_AGGR_INTERFACE_CREDENTIALS' and INDEX_TYPE='NORMAL';
select 'alter index ' ||INDEX_NAME||' rebuild online;' from user_indexes where TABLE_NAME='L_AGGR_INTER_CRED_ATTRIBUTE' and INDEX_TYPE='NORMAL';
select 'alter index ' ||INDEX_NAME||' rebuild online;' from user_indexes where TABLE_NAME='L_AGGR_MV_PROPERTY' and INDEX_TYPE='NORMAL';
select 'alter index ' ||INDEX_NAME||' rebuild online;' from user_indexes where TABLE_NAME='L_AGGR_VALUES_MV_PROPERTY' and INDEX_TYPE='NORMAL';
select 'alter index ' ||INDEX_NAME||' rebuild online;' from user_indexes where TABLE_NAME='LOGICAL_AGGREGATION' and INDEX_TYPE='NORMAL';
select 'alter index ' ||INDEX_NAME||' rebuild online;' from user_indexes where TABLE_NAME='NGN_ENTITY_NODE' and INDEX_TYPE='NORMAL';
select 'alter index ' ||INDEX_NAME||' rebuild online;' from user_indexes where TABLE_NAME='WOS_LOGICAL_AGGREGATION' and INDEX_TYPE='NORMAL';
select 'alter index ' ||INDEX_NAME||' rebuild online;' from user_indexes where TABLE_NAME='WOS_REQUIRED_ATTRIBUTE' and INDEX_TYPE='NORMAL';
select 'alter index ' ||INDEX_NAME||' rebuild online;' from user_indexes where TABLE_NAME='WOS_LOGICAL_CONFIGURATION' and INDEX_TYPE='NORMAL';
select 'alter index ' ||INDEX_NAME||' rebuild online;' from user_indexes where TABLE_NAME='WOS_ATTR' and INDEX_TYPE='NORMAL';
 
select 'alter index ' ||INDEX_NAME||' rebuild online;' from user_indexes where TABLE_NAME='WOS_OTHER_NODE_IP_TYPE' and INDEX_TYPE='NORMAL';
select 'alter index ' ||INDEX_NAME||' rebuild online;' from user_indexes where TABLE_NAME='WOS_REQUIRED_PROPERTY' and INDEX_TYPE='NORMAL';
select 'alter index ' ||INDEX_NAME||' rebuild online;' from user_indexes where TABLE_NAME='WOS_PROTOCOLS' and INDEX_TYPE='NORMAL';
select 'alter index ' ||INDEX_NAME||' rebuild online;' from user_indexes where TABLE_NAME='WOS_CREDENTIAL_ATTRIBUTES' and INDEX_TYPE='NORMAL';
spool off
@/tmp/rebuild_idx_${v_schema}.sql
exit;
EOF
echo "done"
echo "logs index under /tmp/rebuild_idx_INEM_REP.log"

Working with working set in eclipse

Working with working set in eclipse:

Let assume an application made of many related  eclipse (for example a gui project many depends on many projects of back end layer). To have a working compilation no choice, you have to import all projects in eclipse. But it is noising have so many projects you don’t work to on project explorer only for compilation needs (see example). To avoid that problem you may use eclipse working set which allows you to have a restricted view of only projects of your interest (other projects still live behind)

See example by pictures:
Step1 = 2 projects in my workspace -> select working set menu




Step2= create a new working set

Step3 = select projects belonging to working set



Step4 = from fist menu (see figure for step 1) select working set you want work to



giovedì 28 giugno 2012

NAMED STORE PROCEDURE SAMPLE






/* Lo script ripulisce di dati antecedenti alla data memorizzata nella variabile dateFrom.
* La variabile daysFrom indica di quanti giorni voglio arretrare la data di sistema.
*/
create or replace
PROCEDURE PURGE_CM_ORDERS_TABLES AS
daysFrom NUMBER := 45;
dateFrom DATE := SYSDATE - daysFrom;
begin
delete from service_request_tracking s
where s.REQUEST_ID in (
select r1.REQUEST_ID from request r1
where r1.REQUEST_DATE <= dateFrom
);
delete from iemx_order ord
where ord.REQUEST_ID in (
select r.REQUEST_ID from request r
where r.REQUEST_DATE <= dateFrom
);
delete from order_to_fullqualified_name fqn
where fqn.REQUEST_ID in (
select r1.REQUEST_ID from request r1
where r1.REQUEST_DATE <= dateFrom
);
delete from request_info info
where info.REQUEST_ID in (
select r.REQUEST_ID from request r
where r.REQUEST_DATE <= dateFrom
);
delete from request r
where r.REQUEST_DATE <= dateFrom;
delete from IEMX_APP.WORKLOG w
where w.CONFIGORDERID in (
select conf.CONFIGORDERID from IEMX_APP.CONFIGORDER conf
where conf.CREATIONDATE <= dateFrom
);
delete from IEMX_APP.CONFIGORDER conf
where conf.CREATIONDATE <= dateFrom;
COMMIT;
END PURGE_CM_ORDERS_TABLES;
/
 

mercoledì 23 maggio 2012

Intercepting Java Web Server Startup And ShootDown with servlet and JVM hook

In this sample you may quite easy intercept events of Web Server starting completed and shut down  done implementing a Servlet.
When init() metod is invoked on servlet you may suppose that web server has completed start procedure (usually gui are latest module deployed and moreover are deployed only if all dependent modules are correctly deployed).
To intercept shutdown event you may use JVM shootdown hook (Runtime.getRuntime stands for JVM in sample) so when shutdown signal is sent to JVM your thread starts.

After coding servlet don't miss to configure your web.xml file.

Here web.xml fragment
     <servlet>
        <servlet-name>StartAndStopListener</servlet-name>
        <servlet-class>com.italtel.snodo.util.servlet.StartAndStopListener</servlet-class>
        <load-on-startup> 1 </load-on-startup>
    </servlet>


    <servlet-mapping>
        <servlet-name>StartAndStopListener</servlet-name>
        <url-pattern>/StartAndStopListener</url-pattern>
    </servlet-mapping>
   
   
And here servlet code



import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServlet;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import com.italtel.systmng.applog.api.ApplogInterface;



public class StartAndStopListener  extends HttpServlet {
   
   
    /**
     *
     */
    private static final long serialVersionUID = -4370442950501287760L;

    /*
     * Logger di classe
     */
    private Logger logger = LogManager.getLogger(this.getClass());
    private ApplogInterface applogger;
    private Thread myShutDownInstance;
   
    public static final String APPLICATION_NAME = "CM_NOFUN_JBOSS_BE";
    public static final String EVENT_NAME_START = "CM_GUI_STARTUP";
    public static final String EVENT_NAME_STOP  = "CM_GUI_SHUTDOWN";
    public static final String EVENT_TYPE_START = "CLEARED" ;
    public static final String EVENT_TYPE_STOP  = "P_WARNING" ;


   


    @Override
    public void init() {
        applogger = new ApplogInterface();
        myShutDownInstance = new MyShutdown(applogger);
        registerJVMStop();
        Date date = new Date ();
        String appLogDateString = getDateAppLog(date);
        logger.info("CONF.WAR STARTING EVENT INTERCEPTED");
        this.applogger.sendMsg(APPLICATION_NAME, EVENT_NAME_START , EVENT_TYPE_START, appLogDateString, "CM Gui Started");
        logger.info("CONF.WAR STARTING EVENT INTERCEPTED");
    }

   

   
    private void registerJVMStop()  {
        Runtime.getRuntime().addShutdownHook(this.myShutDownInstance);

    }


   
    public static String getDateAppLog(Date date){
        String ret;
        String dateFormat = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        ret = sdf.format(date);
        return ret;
    }
   
}


class MyShutdown extends Thread {
    private Logger logger = LogManager.getLogger(this.getClass());
   
    private ApplogInterface applogger;
   
    public MyShutdown(ApplogInterface applogger) {
        super();
        this.applogger = applogger;
        logger.info("MyShutDown thread created");
    }
   
    public void run() {
        try {
            logger.info("JVM STOPPING EVENT INTERCEPTED");
            Date date = new Date ();
            String appLogDateString = StartAndStopListener.getDateAppLog(date);
            this.applogger.sendMsg(StartAndStopListener.APPLICATION_NAME, StartAndStopListener.EVENT_NAME_STOP ,StartAndStopListener.EVENT_TYPE_STOP, appLogDateString, "CM  ShutDown Executed");

        } catch (Exception ee) {
            ee.printStackTrace();
        }   
    }
}

lunedì 14 maggio 2012

Eclipse projects Cannot run program error=87

Problem occured with Ecplipse Elios running on Windows 7 System

DESCRIPTION
Sometimes some eclipse project doesn't start while others does.
Not running projects launch this error message :
Exception occurred executing command line.
Cannot run program "C:\Program Files\Java\jdk1.6.0_16\bin\javaw.exe" (in directory "C:\paolo_lavoro\rep_svn\branches\cm\br-dev-inem-cm-2.3\iEMX-GUI"): CreateProcess error=87, Parametro non corretto







That error reason is quite simple: CLASSPATH is too long ; perhaps you have too many project dependencies in not running projects while shorter projects dependencies in running projects.





SOLUTION (Workaround)
One solution is keep all dependencies while compiling project and removing them while run classes.




domenica 13 maggio 2012

JAVA COLLECTIONS Framework



BASIC FEATURES

v  Overview of Collection framework  interfaces  and implementations. 
v  The equals() and hashCode() contracts.
v   Interface implementation classes.
v  Sorting Items (Comparable interface and Comparators)
v  Generics & Collections

ADVANCED FEATURES

v  Collections in multithread environment:

Overview of Collection framework  interfaces  and implementations. 


 4 basic flavors:
Lists = Lists of objects (List interface)
Sets = Unique Objects (Set Interface)
Maps =  objects referenced by and unique identifier (object)   (Map interface)
Queues = Objects arranged by the order in which they are to be processed (not covered )

Most remarkable notes:
·         Lists support duplicate items
·         Sets doesn’t support duplicate items
·         Maps doesn’t support duplicate keys


Interfaces
Map
Set
List
(Ordered)
(Sorted)
Classes
HashMap
X


No
No
Hashtable
X


No
No
TreeMap
X


 Sorted. See  ->
By natural order
or custom comparison rule
LinkedHashMap
X


By insertion order
or last access order(LRU) 
No
HashSet

X

No
No
TreeSet

X

Sorted. See ->
By natural order
or custom comparison rule
LinkedHashSet

X

By insertion order
No
ArrayList


X
By index
No
Vector


X
By index
No
LinkedList


X
By index
No
…..








The equals() and hashCode() contracts.


·         What is the meaning of term duplicate items not supported for Java Objects ?
o   Analyze difference between operator “==” and equals() methods:
§  “==” operator checks only for identical references
§  equals() method tests if 2 objects are equals.

·         What it means if you don’t override equals()?
o   Default equals implementation uses only the “==” operator for comparison (String exception below)
o   You shouldn’t use those objects as keys in Maps and put them in Sets as Sets has not conceptual duplicates.

·         equals() contract (useful for test):
o   reflexive
o   symmetric
o   transitive
o   consistent
o   if x != null x.equals(null) is false

·         But overriding equals() is not enough !!  In fact see example EqualsTest.java applied to HashMap. You must override also hashCode() method according this table.  The more efficient is hashCode() implementation the better performance access you ‘ll get.
In fact you can have your hashCode() method returning always the same value (es. x.hashCode() = 1) but this means that all objects will be stored in Hash at the same bucket. 


Condition
Required
Not Required (but allowed)
x.equals(y) == true
x.hashCode() == y.hashCode()

x.hashCode() == y.hashCode()

x.equals(y) == true
x.equals(y) == false

No hashCode() requierements
x.hashCode() != y.hashCode()
x.equals(y) == false



import java.util.HashSet;

public class EqualsTest {
       public static void main (String [] args) {
             testOnlyEquals();
             testHashCodeAndEquals();         
       }
      
       static void testOnlyEquals() {
             EqualsOnlyClass i1 = new EqualsOnlyClass("pippo");
             EqualsOnlyClass  i2 = new EqualsOnlyClass("pippo");
             System.out.println("are equals? " + i1.equals(i2));
             HashSet <EqualsOnlyClass> set = new HashSet <EqualsOnlyClass>();
             set.add(i1);
             set.add(i2);
             set.size();
             System.out.println("set Size= " + set.size());
       }
       static void testHashCodeAndEquals() {
             EqualsAndHash i1 = new EqualsAndHash("pippo");
             EqualsAndHash  i2 = new EqualsAndHash("pippo");
             System.out.println("are equals? " + i1.equals(i2));
             HashSet <EqualsAndHash> set = new HashSet <EqualsAndHash>();
             set.add(i1);
             set.add(i2);
             set.size();
             System.out.println("set Size= " + set.size());
       }
      
}


class  EqualsOnlyClass{
      
       public java.lang.String parameter;
      
       public EqualsOnlyClass (String a){
             this.parameter = a;
       }
      
      
       public boolean equals (Object anotherInstance){
             boolean result = false;
             if (anotherInstance instanceof EqualsOnlyClass ){
                    result =  this.parameter.equals(((EqualsOnlyClass) anotherInstance).parameter);
             }
             return result;
       }     
}


class  EqualsAndHash extends EqualsOnlyClass{
      
       public EqualsAndHash (String a){
             super(a);
       }
      
      
       public int hashCode (){
              return this.parameter.hashCode();
       }

}
Output is :
are equals? true
set Size= 2
are equals? true
set Size= 1


Strings behaviors with == and equals(). Code sample:


RUN CODE STRINGTEST.class

OUTPUT:
testA
 s1 = "a"
 s2 = "a"
 s1 == s2 is true
 s1.equals(s2) is true

testB
 s1 = new String("a")
 s2 = new String("a")
 s1 == s2 is false
 s1.equals(s2) is true   

 * Comments :
 * String offeres many constructors for Strings:
 *   in testA
*   String s1 = "a"; create a literal "a" in pool memory and s1 refers to it
      *   String s2 = "a"; s2 refers to same previous literal in pool.  

*   otherwise in testB   
       *    String s1 = new String("a") ;  because we use new keyword a new String object is created in not  pool memory (s1 refers to it) and  in addiction literal "a" is placed  in pool memory;
       *    String s2 = new String("a") ;  because we use new keyword a new String object is created in not  pool memory and (different from previous) s2 refers to it
       
     
Source
public class StringTest {

         public static void main (String [] args){
                   testA();
                  
                   testB();
         }
        
         static void testA(){
                   System.out.println (" testA");
                   // good memory usage!!  RECOMENDED constructor
                   String s1 = "a";
                   String s2 = "a";
                   System.out.println (" s1 = \"a\"");
                   System.out.println (" s2 = \"a\"");
                   if (s1 == s2 ){
                            System.out.println (" s1 == s2 is true");
                   } else {
                            System.out.println (" s1 == s2 is false");
                   }
                   if (s1.equals(s2)  ){
                            System.out.println (" s1.equals(s2) is true ");
                   } else {
                            System.out.println (" s1.equals(s2) is false ");
                   }
         }
        
         static void testB(){
                   System.out.println (" testB");
                   // waste memory !! NOT RECOMENDED CONSTRUCTOR FOR STRINGS
                   String s1 = new String ("a");
                   String s2 = new String("a");
                   System.out.println (" s1 = new String(\"a\")");
                   System.out.println (" s2 = new String(\"a\")");
                   if (s1 == s2 ){
                            System.out.println (" s1 == s2");
                   } else {
                            System.out.println (" s1 == s2 is false");
                   }
                   if (s1.equals(s2)  ){
                            System.out.println (" s1.equals(s2) is true ");
                   } else {
                            System.out.println (" s1.equals(s2) is false ");
                   }
         }

         /**
          * Comments :
          * String offeres many constructors for Strings:
          *   in testA
          *   String s1 = "a"; create a literal "a" in pool memory ans s1 refers to it
     *   String s2 = "a"; s2 refers to same previous literal in pool.
          *  
          *   otherwise in testB      
          *    String s1 = new String("a") ;  because we use new keyword a new String object is created in not  pool memory (s1 refers to it) and  in addiction literal "a" is placed  in pool memory;
          *    String s2 = new String("a") ;  because we use new keyword a new String object is created in not  pool memory and (different from previous) s2 refers to it
          */     
}

Interface implementation classes.


Lists
ArrayList =suitable  for fast (constant time) access without a lot of insertion and deletion. Its element are ordered by index position but not sorted. Duplicate allowed.
Vector = old synchronized version of Array.
LinkedList= elements are ordered by index position and are double linked to one another. This linkage offers additional methods to add and remove elements from the beginning and the end. Iteration is more slowly than ArrayList but it is sa good choice if you nedd good performance in adding and removing items. Duplicate allowed.

Set
HashSet = unsorted and unordered Set. Use this class when you want a collection with no duplicates and you don’t care about order when iterate over items.
LinkedHashSet = An ordered version of HashSet. Use this class when you care about order when iterate over items. Order is equal to insertion order.
TreeSet = this is  a sorted collection . elements are sorted in natural order (more on sorting later). Null element not admitted (unsortable).

Map
You map a unique key (the ID) to  a specific  value;  both key and value are objects.  You may search for a value object based on key , ask for collection of just keys or collection of just values. Like Set , maps rely on equals() for keys comparison.
HashMap = HasMap allows one null key and multiple null value objects in collection. Collection elements are unsorted and unordered.
Hashtable = HashMap synchronized version (from older java version). Moreover no null key or value is admitted.
LinkedHashMap= Adds ordering capability to map. Null key is admitted.  Default ordering is insertion order (iterators for key set and value set are available but index are not supported) but a special constructor is provided for access order:
 public LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder)
Constructs an empty LinkedHashMap instance with the specified initial capacity, load factor and ordering mode.
Parameters:
initialCapacity - the initial capacity
loadFactor - the load factor
accessOrder - the ordering mode - true for access-order, false for insertion-order

Expected performance for LinkedHashMap  is faster iteration time  and slower insertion and deletion  compared to HashMap .
TreMap = like TreeSet this is a sorted collection. Key objects  are sorted in natural order (more on sorting later). Null key is not admitted (not sortable).
                                                                                         

Sorting Items (Comparable interface and Comparators)



Let’s see add method of TreeSet class
public boolean add(E e)
Parameters:
e - element to be added to this set

Throws:
ClassCastException - if the specified object cannot be compared with the elements currently in this set
NullPointerException - if the specified element is null and this set uses natural ordering, or its comparator does not permit null elements

How get objects sortable? You have basically 2 choices:
a)      Made your object implement Comparable interface.
b)      Define a Comparator class which deals with your objects.
 Tips:
-use choice a) if you may operate on your own objects and if you need only 1 comparison algorithm.
-use choice b) if you can’t change on object to compare and/or you want more than 1 comparison on objects.
- Collections utility class and Array utility class permit to sort also Arrays and Collections (es ArrayList) by static methods
Java.util.Collections
static
<T extends Comparable<? super T>> void
sort(List<T> list)
          Sorts the specified list into ascending order, according to the natural ordering of its elements.
static <T> void
sort(List<T> list, Comparator<? super T> c)
          Sorts the specified list according to the order induced by the specified comparator.

Java.util.Arrays
static
<T> void
sort(T[] a, Comparator<? super T> c)
          Sorts the specified array of objects according to the order induced by the specified comparator.
static void
sort(Object[] a)
          Sorts the specified array of objects into ascending order, according to the
natural ordering of its elements.

Java.lang.Comparable interface

int compareTo(T o)
Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
Int x = thisObject.compareTo(anotherObject)
x <    0  if thisObject < anotherObject
x  == 0  if thisObject == anotherObject
x > 0  if thisObject > anotherObject
The implementor must ensure sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) for all x and y. (This implies that x.compareTo(y) must throw an exception iff y.compareTo(x) throws an exception.)
The implementor must also ensure that the relation is transitive: (x.compareTo(y)>0 && y.compareTo(z)>0) implies x.compareTo(z)>0.
Finally, the implementor must ensure that x.compareTo(y)==0 implies that sgn(x.compareTo(z)) == sgn(y.compareTo(z)), for all z.
It is strongly recommended, but not strictly required that (x.compareTo(y)==0) == (x.equals(y)). Generally speaking, any class that implements the Comparable interface and violates this condition should clearly indicate this fact. The recommended language is "Note: this class has a natural ordering that is inconsistent with equals."
EXAMPLE: run OrdinamentoArgs.java –
import java.util.*;

public class OrdinamentoArgs {

        
         public static void main (String [] args) {
                
                 /**
                  * soluzione n1
                  */
                 /**
                 Integer [] myIntegerArray = new Integer[args.length];
                 for (int i =0 ; i < args.length;  i++ ){
                          myIntegerArray[i] = Integer.valueOf(args[i]);
                 }
                
                 List <Integer> integerList = Arrays.asList(myIntegerArray);
                 Collections.sort(integerList);
                 System.out.println("debug");
                
                 for (Integer a : integerList) {
                          System.out.println(a);
                 }
                 **/
                
                 /**
                  * sol. n2 nesssun indice di array usato
                  */
                 ArrayList <Integer> destination = new ArrayList <Integer> ();
                 for (String aString : args ){
                          destination.add(  Integer.valueOf(aString) );
                 }
                 Collections.sort(destination);
                
                 LinkedHashMap <Integer, Integer> lMap = new LinkedHashMap <Integer, Integer> ();
                 for (Integer myKey : destination ) {
                          lMap =insertInMap(myKey, lMap);
                 }
                
                 for (  Integer key    : lMap.keySet() ) {
                          System.out.println(key + " presente  " + lMap.get(key) + "volte" );
                 }
                
         } 
        
        
         private static LinkedHashMap <Integer, Integer> insertInMap ( Integer key,  LinkedHashMap <Integer, Integer> lMap){
                 if (lMap.containsKey(key)  ){
                          Integer value = lMap.get(key);
                          lMap.put(key, value + 1);
                         
                 } else {
                          lMap.put(key , Integer.valueOf(1));
                 }
                
                 //LinkedHashMap <Integer, Integer>  result =
                
                 return lMap ;
         }
}
See in code 2 for loops used:
According pre java 1.5 generics
                 Integer [] myIntegerArray = new Integer[args.length];
                 for (int i =0 ; i < args.length;  i++ ){
                          myIntegerArray[i] = Integer.valueOf(args[i]);
                 }

According new java 1.5 declaration stile
                 for (String aString : args ){
                          destination.add(  Integer.valueOf(aString) );
                 }


Generics & Collections

Design goal of generics:
-          Ensure class type check at compile time instead of throwing ClassCastException at runtime.
-          Enhanced for loop.
-          Autoboxing (no cast required)
Example
List myIntList = new LinkedList(); // 1
myIntList.add(new Integer(0)); // 2
Integer x = (Integer) myIntList.iterator().next(); // 3

List<Integer> myIntList = new LinkedList<Integer>(); // 1’
myIntList.add(new Integer(0)); //2’
Integer x = myIntList.iterator().next(); // 3’


Polymorphism and generics


Generics support polymorphism is a such different way compared to Arrays:
List <Number> list = new ArrayList <Integer>();
list.add(new Integer(0));
//NO!! – WRONG type <Number>  in declaration must match with type  <Integer> of object subclass is not allowed.


List <Number> list = new ArrayList <Number>();
list.add(new Integer(0));
// YES!!  You can add a subclass instance
Number o = list.get(0); // NO CAST REQUIRED
Integer o1 = (Integer) list.get(0); // CAST REQUIRED




Wildcard generics - Using typed collections in methods

Polymorphism is supported by generics using special wildcards  :

? = any type
<T> = Class type
<E> = element of collection
<K,V> = key , value in a Map
extends
super
examples:
java.util
Class TreeSet<E>
TreeSet(Collection<? extends E> c)
          Constructs a new tree set containing the elements in the specified collection, sorted according to the natural ordering of its elements.
TreeSet(Comparator<? super E> comparator)
          Constructs a new, empty tree set, sorted according to the specified comparator.

PECS = Producer Extends, Consumer Super
Apply constructor to these sample classes
Class Person
name

Class  SportSupporter extends Person
favouriteTeam

And define 2 sample Comparators
Comparator <Person> (sorting by name)
Comparator < SportSupporter>  (sorting by name and favouriteTeam)
Try to figure out why first constructor uses “extends” keywords while second “super” keyword

Collections in multithread environment

Most of Collection are unsynchronized so when you have multiple thread accessing collection you should manage correctly access to collection.    java.util.ConcurrentModificationException (extends RuntimeException) is thrown for if  one thread to modify a Collection while another thread is iterating over it. To solve this issue basically you have three different options:
a)      Since java 1.2 you may have s synchronized version of collection using  Collections static utilities methods. The drawback is that all collection methods are synchronized – the problem is that also iterator should be thread safe
public static <T> List<T> synchronizedList(List<T> list)
Returns a synchronized (thread-safe) list backed by the specified list. In order to guarantee serial access, it is critical that all access to the backing list is accomplished through the returned list.
It is imperative that the user manually synchronize on the returned list when iterating over it:
  List list = Collections.synchronizedList(new ArrayList());
      ...
  synchronized(list) {
      Iterator i = list.iterator(); // Must be in synchronized block
      while (i.hasNext())
          foo(i.next());
  }
 
b)      You may directly synchronize a wrapper collection class.see http://paolobacco.blogspot.it/2012/05/multi-thread-java-synchronized-and.html


c)       You may rely upon new java 1.5 java.util.concurrent packadge
When many threads are expected to access a given collection, a ConcurrentHashMap is normally preferable to a synchronized HashMap, and a ConcurrentSkipListMap is normally preferable to a synchronized TreeMap. A CopyOnWriteArrayList is preferable to a synchronized ArrayList when the expected number of reads and traversals greatly outnumber the number of updates to a list.
The "Concurrent" prefix used with some classes in this package is a shorthand indicating several differences from similar "synchronized" classes. For example java.util.Hashtable and Collections.synchronizedMap(new HashMap()) are synchronized. But ConcurrentHashMap is "concurrent". A concurrent collection is thread-safe, but not governed by a single exclusion lock. In the particular case of ConcurrentHashMap, it safely permits any number of concurrent reads as well as a tunable number of concurrent writes. "Synchronized" classes can be useful when you need to prevent all access to a collection via a single lock, at the expense of poorer scalability. In other cases in which multiple threads are expected to access a common collection, "concurrent" versions are normally preferable. And unsynchronized collections are preferable when either collections are unshared, or are accessible only when holding other locks.
Most concurrent Collection implementations (including most Queues) also differ from the usual java.util conventions in that their Iterators provide weakly consistent rather than fast-fail traversal. A weakly consistent iterator is thread-safe, but does not necessarily freeze the collection while iterating, so it may (or may not) reflect any updates since the iterator was created.


References

Sun Certification Java Program 1.5-1.6