UTILITIES @ WORK           - don’t reinvent when it is ready to use
AGENDA Discussion on apache commons utilities Java Concurrency Framework Mutable vs. Immutable                         ...
APACHE COMMONS UTILITIES Configuration Lang IO BeanUtils                           3
APACHE COMMONS - CONFIGURATION org.apache.commons.configuration To load a properties file:  PropertiesConfiguration conf...
APACHE COMMONS – CONFIGURATION (CONT..)                            Example Properties files         usergui.properties    ...
APACHE COMMONS – CONFIGURATION (CONT..)Sample Code                                          6
7
APACHE COMMONS – LANG StringUtils ToStringBuilder ArrayUtils                        8
APACHE COMMONS – LANG - STRINGUTILS org.apache.commons.lang.StringUtils Methods:    1.   isEmpty :- Checks if a String i...
APACHE COMMONS – LANG – STRINGUTILS (CONT…)String str1 = null;boolean result = false;result = StringUtils.isEmpty(str1); /...
APACHE COMMONS – LANG - TOSTRINGBUILDERpublic class ToStringBuilderDemo {  public static void main(String args[]){    Syst...
APACHE COMMONS – LANG - ARRAYUTILSimport java.util.Arrays;import org.apache.commons.lang.ArrayUtils;public class ArrayUtil...
I I I I O O O  I III I       I O O O        I O O O I II I I O O O O Input Output       13
APACHE COMMONS – IO IOUtils FileUtils FileSystemUtils FileFilter LineIterator                      14
APACHE COMMONS – IO (CONT…)Task of reading bytes from a URL:                                    TRADITIONAL               ...
APACHE COMMONS – IO (CONT…)   File dir = new File(".");   String[] files = dir.list( new                  PrefixFileFilter...
17
ExecutorFramework            18
SEQUENTIAL WEB SERVERclass SingleThreadWebServer{  public static void main(String args[]){    ServerSocket socket = new Se...
WEB SERVER THAT STARTS A NEW THREAD FOR EACH REQUESTclass ThreadPerTaskWebServer{  public static void main(String args[]){...
WEB SERVER USING A THREAD POOLclass TaskExecutionWebServer{  private static final int NTHREADS = 100;  private static fina...
synchronization        volatile        atomic                   22
SYNCHRONIZATION   Synchronization is built around an internal entity known as the    intrinsic lock or monitor lock. Intr...
VOLATILE A volatile variable is not allowed to have a local copy  of a variable that is different from the value currentl...
ATOMIC INTEGERpublic class Counter {          private AtomicInteger count = new AtomicInteger(0);         public void incr...
MUTABLE VS. IMMUTABLE Mutable: When we have a reference to an instance of  an object, the contents of that instance can b...
BUILDING AN IMMUTABLE CLASS Make all fields private. Don’t provide mutators (setter methods) Ensure that methods cant b...
public final class BetterPerson{         private String firstName;         private String lastName;         private Date d...
29
- PRAMOD           30
Upcoming SlideShare
Loading in …5
×

Use of Apache Commons and Utilities

4,346 views

Published on

Published in: Technology
0 Comments
6 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
4,346
On SlideShare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
103
Comments
0
Likes
6
Embeds 0
No embeds

No notes for slide

Use of Apache Commons and Utilities

  1. 1. UTILITIES @ WORK - don’t reinvent when it is ready to use
  2. 2. AGENDA Discussion on apache commons utilities Java Concurrency Framework Mutable vs. Immutable 2
  3. 3. APACHE COMMONS UTILITIES Configuration Lang IO BeanUtils 3
  4. 4. APACHE COMMONS - CONFIGURATION org.apache.commons.configuration To load a properties file: PropertiesConfiguration config = new PropertiesConfiguration(“usergui.properties”); If we do not specify an absolute path, the file will be searched automatically in the following locations:  in the current directory  in the user home directory  in the classpath If a property is named “include” and the value of that property is the name of a file on the disk, that file will 4 be included into the configuration.
  5. 5. APACHE COMMONS – CONFIGURATION (CONT..) Example Properties files usergui.properties color.properties window.width = 500 colors.background = #FFFFFF window.height = 300 colors.foreground = #000080 include = color.properties # chart colors colors.background = #FFFFFF colors.pie = #FF0000, #00FF00 colors.foreground = #000080 # chart colors colors.pie = #FF0000, #00FF00 5
  6. 6. APACHE COMMONS – CONFIGURATION (CONT..)Sample Code 6
  7. 7. 7
  8. 8. APACHE COMMONS – LANG StringUtils ToStringBuilder ArrayUtils 8
  9. 9. APACHE COMMONS – LANG - STRINGUTILS org.apache.commons.lang.StringUtils Methods: 1. isEmpty :- Checks if a String is empty (“”) or null. 2. isBlank :- Checks if a String is whitespace, empty or null. 3. isAlpha :- Checks if a String contains only alphabets 4. isNumeric :- Checks if a String contains only nuerics 5. defaultIfEmpty(String str, String defString) :- If str is empty or null, “defString” is returned else “str” is returned 6. reverseDelimited :-Reverses a String that is delimited by a specific character 7. leftPad / rightPad 9
  10. 10. APACHE COMMONS – LANG – STRINGUTILS (CONT…)String str1 = null;boolean result = false;result = StringUtils.isEmpty(str1); // truestr1 = "str123";result = StringUtils.isAlphanumeric(str1); //trueresult = StringUtils.isNumeric(str1); //falsestr1 = "7";str1 = StringUtils.leftPad(str1, 3, 0); //007str1 = "172.168.1.44";str1 = StringUtils.reverseDelimited(str1, .); //44.1.168.172 10
  11. 11. APACHE COMMONS – LANG - TOSTRINGBUILDERpublic class ToStringBuilderDemo { public static void main(String args[]){ System.out.println(new Emp(7,"Java",99.99)); }}class Emp{ int id; String name; double salary; public Emp(int id, String name, double salary){ this.id = id; this.name = name; this.salary = salary; } /* here comes accessors and mutators */ public String toString(){ return ToStringBuilder.reflectionToString(this); 11 }}OUTPUT: com.commons.examples.Emp@10b30a7[id=7,name=Java,salary=99.99]
  12. 12. APACHE COMMONS – LANG - ARRAYUTILSimport java.util.Arrays;import org.apache.commons.lang.ArrayUtils;public class ArrayUtilsDemo { public static void main(String args[]){ String weekends[] = {"friday","saturday","sunday"}; String weekdays[] = {"monday", "tuesday", "wednesday", "thursday"}; String days[] = (String[])ArrayUtils.addAll(weekends, weekdays); System.out.println(ArrayUtils.isEmpty(days)); System.out.println(ArrayUtils.isSameLength(weekends, weekdays)); Integer values[] = new Integer[10]; Arrays.fill(values, 1); int intValues[] = ArrayUtils.toPrimitive(values,0); }} 12
  13. 13. I I I I O O O I III I I O O O I O O O I II I I O O O O Input Output 13
  14. 14. APACHE COMMONS – IO IOUtils FileUtils FileSystemUtils FileFilter LineIterator 14
  15. 15. APACHE COMMONS – IO (CONT…)Task of reading bytes from a URL: TRADITIONAL 15 IOUtils
  16. 16. APACHE COMMONS – IO (CONT…) File dir = new File("."); String[] files = dir.list( new PrefixFileFilter("Test") ); for ( int i = 0; i < files.length; i++ ) { 16 System.out.println(files[i]); }
  17. 17. 17
  18. 18. ExecutorFramework 18
  19. 19. SEQUENTIAL WEB SERVERclass SingleThreadWebServer{ public static void main(String args[]){ ServerSocket socket = new ServerSocket(80); while(true){ Socket connection = socket.accept(); handleRequest(connection); } }}Drawback: thread “main” is responsible for handling allrequests one after the other 19
  20. 20. WEB SERVER THAT STARTS A NEW THREAD FOR EACH REQUESTclass ThreadPerTaskWebServer{ public static void main(String args[]){ ServerSocket socket = new ServerSocket(80); while(true){ final Socket connection = socket.accept(); Runnable r = new Runnable(){ public void run(){ handleRequest(connection); } }; new Thread(r).start(); }}} 20Drawback: may cause “OutOfMemory” error as there isno boundary on thread creation.
  21. 21. WEB SERVER USING A THREAD POOLclass TaskExecutionWebServer{ private static final int NTHREADS = 100; private static final Executor exec = Executors.newFixedThreadPool(NTHREADS); public static void main(String args[]){ ServerSocket socket = new ServerSocket(80); while(true){ final Socket connection = socket.accept(); Runnable task = new Runnable(){ public void run(){ handleRequest(connection); } }; exec.execute(task); } 21 }}
  22. 22. synchronization volatile atomic 22
  23. 23. SYNCHRONIZATION Synchronization is built around an internal entity known as the intrinsic lock or monitor lock. Intrinsic lock play a role in both aspects of synchronization: enforcing exclusive access to an object’s state and establishing happens-before relationships that are essential to visibility. Drawbacks:  Locking  Blocking  Context Switching  Possibility of Deadlock 23
  24. 24. VOLATILE A volatile variable is not allowed to have a local copy of a variable that is different from the value currently held in “main” memory. Volatile variables cannot be used to construct atomic compound actions(i++). This means that volatile variables cannot be used:  when one variable depends on another  when the new value of a variable depends on its old value. 24
  25. 25. ATOMIC INTEGERpublic class Counter { private AtomicInteger count = new AtomicInteger(0); public void incrementCount() { count.incrementAndGet(); } public int getCount() { return count.get(); }} 25
  26. 26. MUTABLE VS. IMMUTABLE Mutable: When we have a reference to an instance of an object, the contents of that instance can be altered. For Ex: class Person, Employee, java.math.BigInteger, etc. Immutable: When you have a reference to an instance of an object, the contents of that instance cannot be altered. For Ex: all wrapper classes (Integer,String,etc) 26
  27. 27. BUILDING AN IMMUTABLE CLASS Make all fields private. Don’t provide mutators (setter methods) Ensure that methods cant be overridden by either making the class final (Strong Immutability) or making your methods final (Weak Immutability). If a field isnt primitive or immutable, make a deep clone on the way in and the way out. 27
  28. 28. public final class BetterPerson{ private String firstName; private String lastName; private Date dob; public BetterPerson( String firstName, String lastName, Date dob){ this.firstName = firstName; this.lastName = lastName; this.dob = new Date( dob.getTime() ); //way in } public String getFirstName(){ return this.firstName; } public String getLastName(){ return this.lastName; } public Date getDOB(){ return new Date( this.dob.getTime() ); //way out } //No mutators at all i.e., setter methods 28}
  29. 29. 29
  30. 30. - PRAMOD 30

×