ARM automatic resource management is another attractive features of Java 7 and project coin. Asname itself implies that now JVM is going to be handling all the external resource and make programmer free to bother about resource management. If my java programmers use any external resources like file, printer or any devices to close after my program execution complete. Normally we close the resources which we have open in beginning of our program or we decide that if program finish normally how to manage the resource or if our program finish abnormally how to close the resource.
ARM- Automatic resource management in Java
Earlier this things or resource management are achieved by try {} catch {} finally block we need to declare resource variable outside of try block and in catch or finally we use this variables for achieving normal execution of program. This JDK7 tutorial is in continuation of my earlier tutorial How to code with multi-cache exception in JDK7 and How to use String in Switch case on JDK7
Example of resource management in java before JDK7
stockQuoteReader = new FileInputStream("StockQuotes.txt");
stockQuoteWriter = new FileOutputStream("StockQuotes.txt");
int var;
while (var = stockQuoteReader.read()) != -1)
stockQuoteWriter.write(var);
} finally {
if (stockQuoteReader!= null)
stockQuoteReader.close();
if (stockQuoteWriter!= null)
stockQuoteWriter.close();
}
But with java 1.7 we manage this thing very easily by try with resource block where inside try we mange this external resources.
Signature of Automatic Resource Management (ARM)
Signature is try(resource1;resource2){}after final resource ;semicolon is not allowed and the resource should be like var=expression type and bydefault all the resources are final type.
What has been added in API for Automatic Resource Management
java.lang.AutoCloseable, interface has been added in API which contains single method close() throws Exception this interface is a parent of java.io.closeable interface so all the input and output devices inherit this property.
Example of Automatic Resource Management (ARM) in JDK7
Here is example of automatic resource management with JDK 1.7 source base. Please make sure you run this with java source 1.7 otherwise you will get compilation error.
FileInputStream stockQuoteReader = new FileInputStream("StockQuotes.txt");
FileOutputStream stockQuoteWriter = new FileOutputStream("StockQuotes.txt")
int var;
while((var= stockQuoteReader.read()) != -1 )
stockQuoteWriter.write();
}
In this code inside try we have declare two file stream one is input file we are reading from one file and writing to another file. After the whole process both streams will be closed automatically either the code has been executed normally or not that means stockQuoteReader.close() and stockQuoteWriter.close() called automatically which is the best part of ARM. If we compare this with earlier example then if any exception occur during input file closing i.e. stockQuoteReader.close() , stockQuoteWriter.close() will never get executed so our code terminated abnormally.
Some important points which needs to be keep in mind when use ARM
§Whatever resource we are using should be subtypes ofAutoCloseable other wise will get compile time error.
§The resources which we are using are closed in reverse order means stockQuoteWriter.close() will be called first then stockQuoteReader.close().
That’s all on new automatic resource management (ARM) feature on JDK7, some how it address the cluttering of code due to checked exception handling and code duplication on several exception cache block.
Object Oriented Design Principles are core of OOPS programming, but I have seen most of Java programmer chasing design patterns like Singleton pattern , Decorator pattern or Observer pattern , and not putting enough attention on learning Object oriented analysis and design. It's important to learn basics of Object oriented programming like Abstraction, Encapsulation, Polymorphism and Inheritance, but same time, it's equally important to know these design principles, to create clean and modular design. I have regularly seen Java programmers and developers of various experience level, who either doesn't heard about these OOPS and SOLID design principle, or simply doesn't know what benefits a particular design principle offers, or how to use these design principle in coding.
Bottom line is, always strive for highly cohesive and loosely couple solution, code or design. Looking open source code from Apache and Sun are good examples of learning Java and OOPS design principles. They show us, how design principles should be used in coding and Java programs. Java Development Kit follows several design principle like Factory Pattern in BorderFactory class, Singleton pattern in Runtime class, Decorator pattern on various java.io classes. By the way if you really interested more on Java coding practices, read Effective Java by Joshua Bloch , a gem by the guy who wrote Java API. My another personal favorite on object oriented design pattern is, Head First Design Pattern by Kathy Sierra and others and Head First Object Oriented Analysis and Design . These books helps a lot to write better code, taking full advantage of various Object oriented and SOLID design principles.
Though best way of learning any design principle or pattern is real world example and understanding the consequences of violating that design principle, subject of this article is Introducing Object oriented design principles for Java Programmers, who are either not exposed to it or in learning phase. I personally think each of these OOPS and SOLID design principle need an article to explain them clearly, and I will definitely try to do that here, but for now just get yourself ready for quick bike ride on design principle town :)
DRY (Don't repeat yourself)
Our first object oriented design principle is DRY, as name suggest DRY (don't repeat yourself) means don't write duplicate code, instead use Abstraction to abstract common things in one place. If you have block of code in more than two place consider making it a separate method, or if you use a hard-coded value more than one time make them public final constant. Benefit of this Object oriented design principle is in maintenance. It's important not to abuse it, duplication is not for code, but for functionality . It means, if you used common code to validate OrderID and SSN it doesn’t mean they are same or they will remain same in future. By using common code for two different functionality or thing you closely couple them forever and when your OrderID changes its format , your SSN validation code will break. So beware of such coupling and just don’t combine anything which uses similar code but are not related.
Encapsulate What Changes
Only one thing is constant in software field and that is "Change", So encapsulate the code you expect or suspect to be changed in future. Benefit of this OOPS Design principle is that Its easy to test and maintain proper encapsulated code. If you are coding in Java then follow principle of making variable and methods private by default and increasing access step by step e.g. from private to protected and not public. Several of design pattern in Java uses Encapsulation, Factory design pattern is one example of Encapsulation which encapsulate object creation code and provides flexibility to introduce new product later with no impact on existing code.
OpenClosed Design Principle
Classes, methods or functions should be Open for extension (new functionality) and Closed for modification. This is another beautiful SOLID design principle, which prevents some-one from changing already tried and tested code. Ideally if you are adding new functionality only than your code should be tested and that's the goal of Open Closed Design principle. By the way, Open Closed principle is "O" from SOLID acronym.
Single Responsibility Principle (SRP)
Single Responsibility Principle is another SOLID design principle, and represent "S" on SOLID acronym. As per SRP, there should not be more than one reason for a class to change, or a class should always handle single functionality. If you put more than one functionality in one Class in Java it introduce coupling between two functionality and even if you change one functionality there is chance you broke coupled functionality, which require another round of testing to avoid any surprise on production environment.
Dependency Injection or Inversion principle
Don't ask for dependency it will be provided to you by framework. This has been very well implemented in Spring framework, beauty of this design principle is that any class which is injected by DI framework is easy to test with mock object and easier to maintain because object creation code is centralized in framework and client code is not littered with that.There are multiple ways to implemented Dependency injection like using byte code instrumentation which some AOP (Aspect Oriented programming) framework like AspectJ does or by using proxies just like used in Spring. See this example of IOC and DI design pattern to learn more about this SOLID design principle. It represent "D" on SOLID acronym.
Favor Composition over Inheritance
Always favor composition over inheritance ,if possible. Some of you may argue this, but I found that Composition is lot more flexible than Inheritance. Composition allows to change behavior of a class at runtime by setting property during runtime and by using Interfaces to compose a class we use polymorphism which provides flexibility of to replace with better implementation any time. Even Effective Java advise to favor composition over inheritance.
Liskov Substitution Principle (LSP)
According to Liskov Substitution Principle, Subtypes must be substitutable for super type i.e. methods or functions which uses super class type must be able to work with object of sub class without any issue". LSP is closely related to Single responsibility principle and Interface Segregation Principle. If a class has more functionality than subclass might not support some of the functionality ,and does violated LSP. In order to follow LSP SOLID design principle, derived class or sub class must enhance functionality, but not reduce them. LSP represent "L" on SOLID acronym.
Interface Segregation principle (ISP)
Interface Segregation Principle stats that, a client should not implement an interface, if it doesn't use that. This happens mostly when one interface contains more than one functionality, and client only need one functionality and not other.Interface design is tricky job because once you release your interface you can not change it without breaking all implementation. Another benefit of this design principle in Java is, interface has disadvantage to implement all method before any class can use it so having single functionality means less method to implement.
Programming for Interface not implementation
Always program for interface and not for implementation this will lead to flexible code which can work with any new implementation of interface. So use interface type on variables, return types of method or argument type of methods in Java. This has been advised by many Java programmer including in Effective Java and head first design pattern book.
Don't do all stuff by yourself, delegate it to respective class. Classical example of delegation design principle is equals() and hashCode() method in Java. In order to compare two object for equality we ask class itself to do comparison instead of Client class doing that check. Benefit of this design principle is no duplication of code and pretty easy to modify behavior.
All these object oriented design principle helps you write flexible and better code by striving high cohesion and low coupling. Theory is first step, but what is most important is to develop ability to find out when to apply these design principle. Find out, whether we are violating any design principle and compromising flexibility of code, but again as nothing is perfect in this world, don't always try to solve problem with design patterns and design principle they are mostly for large enterprise project which has longer maintenance cycle.
The mysqldump client is a backup program o It can be used to dump a database or a collection of databases for backup or transfer to another SQL server (not necessarily a MySQL server). The dump typically contains SQL statements to create the table, populate it, or both. However, mysqldump can also be used to generate files in CSV, other delimited text, or XML format.
To take dump of a mysql table use below command
-------------------------------------------------------
~/mysql/bin/mysqldump -u root database_name ORDERS > orders.txt
1. command to dumb only tables definitions , not the data “ use –d command” if path is not set then you need to run that command from mysql/bin directory
Default Character encoding in Javaor charset is the character encoding used by JVM to convert bytes into Strings or characters when youdon't define java system property "file.encoding". Java gets character encoding by calling System.getProperty("file.encoding","UTF-8") at the time of JVM start-up. So if Java doesn't get any file.encoding attribute it uses "UTF-8" character encoding for all practical purpose e.g. on String.getBytes() or Charset.defaultCharSet().
Most important pointto remember is that Java caches character encoding or value of system property "file.encoding" in most of its core classes like InputStreamReader which needs character encoding after JVM started. so if you change system property "file.encoding" programatically you don't see desired effect and that's why you should always work with your own character encoding provided to your application and if its need to be set than set character encoding or charset while you start JVM.In this Java tutorial we will see couple of different way by which we can set default character encoding or charset of Java and how toretrieve value of charset inside java program.
For those who are not very familiar with character encoding or char-setin Javahere is a layman's introduction "since every data in computer is represented in bytes and Strings are essentially collection of charaters, so to convert bytes into character JVM needs to knowwhich combination of byte represent which character and this is what character encoding tells JVM. Since there are many languagesin world other than English like Hindi, Mandarin, Japanese Kanji etc and so many characters, same combination of bytes can represent different characters in different character encoding andthat's why using correct character encoding is must while converting bytes into String in Java".
How to get Default character encoding in Java ?
There are multiple ways to get default character encoding in Java like by using system property “file.encoding” or by using java.nio.CharSet class. You can choose whatever suits your need. Let’s see them in detail.
1) "file.encoding" system property
Easiest way to get default character encoding in Java is to call System.getProperty("file.encoding"), which will returndefault character encoding if JVM started with -Dfile.encoding property or program has not called System.setProperty("file.encoding, encoding). in later case it may just give value of that system property while various
java.nio.Charset provides a convenient static method Charset.defaultCharset() which returns default character encoding in Java. Check example of getting default char encoding in java using Charset in code section.
3) by using Code InputStreamReader.getEncoding()
This is kind of shortcut where you use default constructor of InputStreamReader and than later gets which character encoding ithas used by calling reader.getEncoding() . See the code example of how to get default character encoding using InputStreamReader.getEncoding() method in code section.
How to set Default character encoding in Java ?
Just like different ways of getting default character encoding or charset in Java there are many ways to set default charset in Java. Here are some of the way:
1. Using System property "file.encoding"
by providing file.encoding system property when JVM starts e.g. java -Dfile.encoding="UTF-8" HelloWorld.
2. Using Environment variable "JAVA_TOOLS_OPTIONS"
If by anyway you don't have control how JVM starts up may be JVM is starting through some scripts which doesn't provide anyway to accept system properties. you can set environment variable JAVA_TOOL_OPTIONS to -Dfile.encoding="UTF-16" or any othercharacter encoding and it will picked up any JVM starts in your windows machine. JVM will also print "Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF16" on console to indicate that it has picked JAVA_TOOS_OPTIONS. here is example of setting default characterencoding using JAVA_TOOLS_OPTIONS
test@system:~/java java HelloWorld
Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF16
defaultCharacterEncoding by property after updating file.encoding : UTF-16
defaultCharacterEncoding by code after updating file.encoding : UTF8
defaultCharacterEncoding by java.nio.Charset after updating file.encoding : UTF-8
Important points to note:
1) JVM caches value of default character encoding once JVM starts and so is the case for default constructors of InputStreamReader and other core Java classes. So calling System.setProperty("file.encoding" , "UTF-16") may not have desire effect.
2) Always work with your own character encoding if you can, that is more accurate and precise way of converting bytes to Strings.
That’s all on how to get default character encoding in Java and how to set it. This becomes more important when you are
writing international application which supports multiple languages. I indeed come across character encoding issues while
writing reports in kanji (Japanese) language which I plan to share in another post, but good knowledge of Character
encoding like UTF-8, UTF-16 or ISO-8859-5 and how Java supports Character Encoding in
ThreadLocal in Java is another way to achieve thread-safety apart from writing immutable classes. If you have been writing multi-threaded or concurrent code in Java then you must be familiar with cost of synchronization or locking which can greatly affect Scalability of application, but there is no choice other than synchronize if you are sharing objects between multiple threads. ThreadLocal in Java is a different way to achieve thread-safety, it doesn't address synchronization requirement, instead it eliminates sharing by providing explicitly copy of Object to each thread. Since Object is no more shared there is no requirement of Synchronization which can improve scalability and performance of application. In this Java ThreadLocal tutorial we will see important points about ThreadLocal in Java, when to use ThreadLocal in Java and a simple Example of ThreadLocal in Java program.
When to use ThreadLocal in Java
Many Java Programmer question where to use ThreadLocal in Java and some even argue benefit of ThreadLocal variable, but ThreadLocal has many genuine use cases and that's why its added in to standard Java Platform Library. I agree though until you are not in concurrent programming, you will rarely use ThreadLocal. below are some well know usage of ThreadLocal class in Java:
1) ThreadLocal are fantastic to implement Per Thread Singleton classes or per thread context information like transaction id.
2) You can wrap any non Thread Safe object in ThreadLocal and suddenly its uses becomes Thread-safe, as its only being used by Thread Safe. One of the classic example of ThreadLocal is sharing SimpleDateForamt. Since SimpleDateFormat is not thread safe, having a global formatter may not work but having per Thread formatter will certainly work.
3) ThreadLocal provides another way to extend Thread. If you want to preserve or carry information from one method call to another you can carry it by using ThreadLocal. This can provide immense flexibility as you don't need to modify any method.
On basic level ThreadLocal provides Thread Confinement which is extension of local variable. while local variable only accessible on block they are declared, ThreadLocal are visible only in Single Thread. No two Thread can see each others ThreadLocal variable. Real Life example of ThreadLocal are in J2EE application servers which uses java ThreadLocal variable to keep track of transaction and security Context. It makes lot of sense to share heavy object like Database Connection as ThreadLocal in order to avoid excessive creation and cost of locking in case of sharing global instance.
/*
* Thread safe format method because every thread will use its own DateFormat
*/ publicstaticString threadSafeFormat(Date date){ DateFormat formatter = PerThreadFormatter.getDateFormatter(); return formatter.format(date); }
}
/*
* Thread Safe implementation of SimpleDateFormat
* Each Thread will get its own instance of SimpleDateFormat which will not be shared between other threads. *
*/ class PerThreadFormatter {
/*
* initialValue() is called
*/
@Override protectedSimpleDateFormat initialValue(){ System.out.println("Creating SimpleDateFormat for Thread : " + Thread.currentThread().getName()); returnnewSimpleDateFormat("dd/MM/yyyy"); } };
/*
* Every time there is a call for DateFormat, ThreadLocal will return calling
* Thread's copy of SimpleDateFormat
*/ publicstaticDateFormat getDateFormatter(){ return dateFormatHolder.get(); } }
If you look the output of above program than you will find that when different thread calls getFormatter() method of ThreadLocal class than its call its initialValue() method which creates exclusive instance of SimpleDateFormat for that Thread. Since SimpleDateFormat is not shared between thread and essentially local to the thread which creates its our threadSafFormat() method is completely thread-safe.
Important points on Java ThreadLocal Class
1. ThreadLocal in Java is introduced on JDK 1.2 but it later generified in JDK 1.4 to introduce type safety on ThreadLocal variable.
2. ThreadLocal can be associated with Thread scope, all the code which is executed by Thread has access to ThreadLocal variables but two thread can not see each others ThreadLocal variable.
3. Each thread holds an exclusive copy of ThreadLocal variable which becomes eligible to Garbage collection after thread finished or died, normally or due to any Exception, Given those ThreadLocal variable doesn't have any other live references.
4. ThreadLocal variables in Java are generally private static fields in Classes and maintain its state inside Thread.
We saw how ThreadLocal in Java opens another avenue for thread-safety. Though concept of thread-safety by confining object to Thread is there from JDK 1.0 and many programmer has there own custom ThreadLocal classes, having ThreadLocal in Java API makes it a lot more easy and standard. Think about ThreadLocal variable while designing concurrency in your application. Don't misunderstood that ThreadLocal is alternative of Synchronization, it all depends upon design. If design allows each thread to have there own copy of object than ThreadLocal is there to use.
Other Java tutorials on Threading you may find useful