Java provides an API to work with compressed file format, zip.
java.util.zip is the package that provides classes to compress and
decompress files in zip format.
This is how to compress a file to zip file format. If we want to compress myfile.txt to myfilezip.zip into the output folder, first myfile.txt is retrieved via FileInputStream. Data read through FileInputStream writes to ZipOutputStream. ZipEntry provides a way to put file entries to ZipOutputStream by putNextEntry method.
public class ConvertFiletoZip {
public void convertToZip(String file, String outputFolder) throws FileNotFoundException, IOException{
try{
//Gets myfile.txt as FileInputStream
File myfile = new File(file);
FileInputStream fileInputStream = new FileInputStream(myfile);
FileOutputStream outputStream = new FileOutputStream(outputFolder + "/myfilezip.zip");
//Creates ZipOutputStream from FileOutputStream
ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
//Creates a ZipEntry and puts it to ZipOutputStream
ZipEntry zipEntry = new ZipEntry("myfile");
zipOutputStream.putNextEntry(zipEntry);
byte[] buffer = new byte[(int) myfile.length()];
int length = 0;
//Reads bytes from FileInputStream and writes to ZipOutputStream
while((length = fileInputStream.read(buffer))>0){
zipOutputStream.write(buffer, 0, length);
}
zipOutputStream.closeEntry();
zipOutputStream.close();
fileInputStream.close();
}catch (IOException e) {
System.out.println("Error occured when zip file is created");
}
}
public static void main(String[] args) throws FileNotFoundException, IOException{
ConvertFiletoZip readZipFile = new ConvertFiletoZip();
readZipFile.convertToZip("/home/kaushalya/myworkspace/ZipManipulation/myfile.txt","/home/kaushalya/myworkspace/ZipManipulation"
);
}
}
In the same way, we can read the zip file through ZipInputStream that is wrapped in FileInputStream. getNextEntry() method is used to get the entries of the zip file. The data of the file entry read to a bytes array is written through FileOutputStream to the output folder.
public class ConvertZiptoFile {
public static final String ZIP_FILE = "/home/kaushalya/myworkspace/ZipManipulation/files/files.zip";
public static final String OUTPUT_FOLDER = "/home/kaushalya/myworkspace/ZipManipulation/files";
public void convertToZipToFile(String zipFile, String outputFolder){
try {
File folder = new File(OUTPUT_FOLDER);
if(!folder.exists()){
folder.mkdir();
}
FileInputStream fileInputStream = new FileInputStream(zipFile);
ZipInputStream zipInputStream = new ZipInputStream(fileInputStream);
ZipEntry zipEntry = null;
while((zipEntry = zipInputStream.getNextEntry()) != null){
System.out.println("File entry : " + zipEntry.getName());
File unzippedFile = new File(folder+"/"+zipEntry.getName());
int length = (int) unzippedFile.length();
byte[] buffer = new byte[length];
FileOutputStream fileOutputStream = new FileOutputStream(unzippedFile);
int len =0;
while((len =zipInputStream.read(buffer))>0){
fileOutputStream.write(buffer, 0, len);
}
zipEntry = null;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args){
ConvertZiptoFile convertZiptoFile = new ConvertZiptoFile();
convertZiptoFile.convertToZipToFile(ZIP_FILE, OUTPUT_FOLDER);
}
}
Monday, February 4, 2013
Friday, January 25, 2013
Singleton Design Pattern - Java
There may be situations that we need
exactly one instance of a class to perform some functionalities.
Singleton design pattern ensures that only one instance of a class is
created and provides a global point of access to the object.
Public class MySingleton(){
private static MySingleton
singletonInstance;
private MySingleton(){
}
public static MySingleton
getSigleton(){
if(singletonInstance = null)
singletonInstance = new MySingleton()
return singletonInstance;
}
}
If we make the constructor of
MySingleton class private, The outside classes can't create instances
of MySingleton class. We can create instances only within MySingleton
class. Therefore, public static getter method is created to give the
instance to outside.
In the situations of using multi
threading, getter method has to be put as synchronized because if two
threads may access the method at the same time and may create two
instances of MySingleton class. But using synchronized keyword may
reduce the performance of the program.
Public class MySingleton(){
private static MySingleton
singletonInstance;
private MySingleton(){
}
public static synchronized MySingleton
getSigleton(){
if(singletonInstance = null)
singletonInstance = new MySingletn()
return singletonInstance;
}
}
The other option to create a Singleton
class is to create the instance when class is loaded. Multi
threading problems may not occur because before any of threads access
the instance is already created when the class is loaded.
Public class MySingleton(){
private static final MySingleton
singletonInstance = new MySingleton()
private MySingleton(){
}
public static MySingleton
getMySingletn (){
return singletonInstance;
}
}
According to the performance of your
program and needs, you can select which method would be better to
create the Singleton class. If you are using several class loaders,
it may create more than one instance. Singleton class cannot be
subclassed because it has a private constructor.
Best way to create a
sigleton class is to use enum as described in Effective Java Reloaded by
Joshua Bloch. Enum guarantees only one instance and thread safety. As the below code, we can declare enum Singleton easily.
public enum MySigleton{
INSTANCE;
public void execute(){
//Other functionalities
}
}
We can get the singleton instance by using MySingleton.INSTANCE.
We can get the singleton instance by using MySingleton.INSTANCE.
Wednesday, February 23, 2011
Web MVC framework-Controllers
Controllers in Web MVC framework, interpret user inputs and transform such input in to a view that is to be viewed by the user. Spring has implemented several controllers in a very abstractive way. They are form-specific controllers, command-based controllers and controllers that execute wizard-style logic. Spring's basic for the controllers is the org.springframework.web.servlet.mvc.Controller interface.
public interface Controller {
ModelAndView handleRequest(
HttpServletRequest request,
HttpServletResponse response) throws Exception;
}
handleRequest method is responsible for handling a request and returning an appropriate modelandview.
AbstractController - Spring controllers inherit the AbstractController to get a basic infrastructure. Then we have to override the method handleRequestInternal(HttpServletRequest, HttpServletResponse). Here is an example.
public class MyController extends AbstractController {
public ModelAndView handleRequestInternal(
HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView mav = new ModelAndView("hello");
mav.addObject("message", "Hello World!");
return mav;
}
}
ParameterizableViewController - This is same as the AbstractController except we can specify the view name that it will return in the web application context.
UrlFilenameViewController - This checks the URL and retrieves the file name of the file request and uses that as the view name.
MultiActionController - This allows the aggregation of multiple request handling methods to one controller.
Command Controllers
Command controllers allow to interact with data objects and dynamically bind the parameters from the HttpServletRequest to the data object specified.
AbstractCommandController - This is a command controller that is capable of binding request parameters to a data object. This controller does not provide form functionality.
AbstractFormController - Provides the form submission support.
SimpleFormController - A form controller that provides even more support when creating a form with a corresponding command object.
public interface Controller {
ModelAndView handleRequest(
HttpServletRequest request,
HttpServletResponse response) throws Exception;
}
handleRequest method is responsible for handling a request and returning an appropriate modelandview.
AbstractController - Spring controllers inherit the AbstractController to get a basic infrastructure. Then we have to override the method handleRequestInternal(HttpServletRequest, HttpServletResponse). Here is an example.
public class MyController extends AbstractController {
public ModelAndView handleRequestInternal(
HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView mav = new ModelAndView("hello");
mav.addObject("message", "Hello World!");
return mav;
}
}
ParameterizableViewController - This is same as the AbstractController except we can specify the view name that it will return in the web application context.
UrlFilenameViewController - This checks the URL and retrieves the file name of the file request and uses that as the view name.
MultiActionController - This allows the aggregation of multiple request handling methods to one controller.
Command Controllers
Command controllers allow to interact with data objects and dynamically bind the parameters from the HttpServletRequest to the data object specified.
AbstractCommandController - This is a command controller that is capable of binding request parameters to a data object. This controller does not provide form functionality.
AbstractFormController - Provides the form submission support.
SimpleFormController - A form controller that provides even more support when creating a form with a corresponding command object.
Tuesday, February 1, 2011
Data binding in Spring MVC
Property editors can be used to bind String to various data types in Spring MVC. Here, enum, int and Date bindings are described.
EnumEditor:
import java.beans.PropertyEditorSupport;
@SuppressWarnings("unchecked")
public class EnumEditor extends PropertyEditorSupport {
private Class clazz;
public EnumEditor(Class clazz) {
this.clazz = clazz;
};
public String getAsText() {
return (getValue() == null ? "" : ((Enum) getValue()).name());
}
public void setAsText(String text) throws IllegalArgumentException {
setValue(Enum.valueOf(clazz, text));
}
EnumClass:
public enum EnumClass{
RED, GREEN, BLUE
}
Register in controller:
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(EnumClass.class,
new EnumEditor(EnumClass.class));
}
import java.beans.PropertyEditorSupport;
@SuppressWarnings("unchecked")
public class IntEditor extends PropertyEditorSupport {
private Class clazz;
public IntEditor(Class clazz) {
this.clazz = clazz;
}
public String getAsText() {
Integer value = (Integer) getValue();
if (value.intValue() == 0) {
return "";
} else {
return value.toString();
}
}
public void setAsText(String value) {
if (value != null && value.length() > 0) {
setValue(Integer.parseInt(value));
} else {
setValue(0);
}
}
Register in controller:
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(int.class, new IntEditor(int.class));
}
@SuppressWarnings("rawtypes")
public class DateEditor extends PropertyEditorSupport {
private Class clazz;
public DateEditor(Class clazz) {
this.clazz = clazz;
}
public void setAsText(String value) {
try {
setValue(new SimpleDateFormat("yyyy-MM-dd").parse(value));
} catch (ParseException e) {
setValue(null);
}
}
public String getAsText() {
return new SimpleDateFormat("yyyy-MM-dd hh:mm a").format((Date) getValue());
}
public void setClazz(Class clazz) {
this.clazz = clazz;
}
public Class getClazz() {
return clazz;
}
}
Register in controller:
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Date.class, new DateEditor(Date.class));
}
- Enum Type
EnumEditor:
import java.beans.PropertyEditorSupport;
@SuppressWarnings("unchecked")
public class EnumEditor extends PropertyEditorSupport {
private Class clazz;
public EnumEditor(Class clazz) {
this.clazz = clazz;
};
public String getAsText() {
return (getValue() == null ? "" : ((Enum) getValue()).name());
}
public void setAsText(String text) throws IllegalArgumentException {
setValue(Enum.valueOf(clazz, text));
}
EnumClass:
public enum EnumClass{
RED, GREEN, BLUE
}
Register in controller:
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(EnumClass.class,
new EnumEditor(EnumClass.class));
}
- Int Type
import java.beans.PropertyEditorSupport;
@SuppressWarnings("unchecked")
public class IntEditor extends PropertyEditorSupport {
private Class clazz;
public IntEditor(Class clazz) {
this.clazz = clazz;
}
public String getAsText() {
Integer value = (Integer) getValue();
if (value.intValue() == 0) {
return "";
} else {
return value.toString();
}
}
public void setAsText(String value) {
if (value != null && value.length() > 0) {
setValue(Integer.parseInt(value));
} else {
setValue(0);
}
}
Register in controller:
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(int.class, new IntEditor(int.class));
}
- Date Type
@SuppressWarnings("rawtypes")
public class DateEditor extends PropertyEditorSupport {
private Class clazz;
public DateEditor(Class clazz) {
this.clazz = clazz;
}
public void setAsText(String value) {
try {
setValue(new SimpleDateFormat("yyyy-MM-dd").parse(value));
} catch (ParseException e) {
setValue(null);
}
}
public String getAsText() {
return new SimpleDateFormat("yyyy-MM-dd hh:mm a").format((Date) getValue());
}
public void setClazz(Class clazz) {
this.clazz = clazz;
}
public Class getClazz() {
return clazz;
}
}
Register in controller:
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Date.class, new DateEditor(Date.class));
}
Tuesday, January 11, 2011
VI Editor in Brief
Introduction
* Screen-based editor
* Case sensitive
* Two modes
o Command mode- perform administrative tasks such as saving files, executing commands, moving the cursor, cutting (yanking) and pasting lines or words, and finding and replacing.
o Insert mode- insert text into the file
Starting the vi Editor
vi filename- creates a new file or open an existing file
vi -R filename- opens an existing file in read only mode
view filename- opens an existing file in read only mode
Inserting text
vi always opens in command mode.
i- insert text before the current cursor location
Esc – back into command mode.
I - Inserts text at the beginning of current line
a - Inserts text after current cursor location
A - Inserts text at the end of current line
o - Creates a new line for text entry below cursor location
O - Creates a new line for text entry above cursor location
Getting out of vi
:q -quit without saving
:wq / ZZ- quite while saving
:w- save the file
:w filename2- save the file by another name
:q!- enforce to quit without saving
Moving cursor in command mode
k – up one line
j - down one line
h - to the left one character one position
l- to the right one character one position
0/| -beginning of line
$ - end of line
:x – to the line number x
Deleting characters
x -Deletes the character under the cursor location
X - Deletes the character before the cursor location
dd- Deletes the line the cursor is on
2dd-Deletes 2 lines
D - Deletes from the cursor position to the end of the current line
Change commands
cc - Removes contents of the line, leaving you in insert mode
r - Replaces the character under the cursor. vi returns to command mode after the replacement is entered
s - Replaces the current character with the character you type. Afterward, you are left in insert mode
Copy and Paste Commands
yy- Copies the current line
p- Puts the copied text after the cursor
P- Puts the yanked text before the cursor
Advanced Commands
J - Join the current line with the next one. A count joins that many lines
<< - Shifts the current line to the left by one shift width
>> - Shifts the current line to the right by one shift width
~ - Switch the case of the character under the cursor
^G - Press CNTRL and G keys at the same time to show the current filename and the status
U- Restore the current line to the state it was in before the cursor entered the line
u - Undo the last change to the file. Typing 'u' again will re-do the change
:f filename - Renames current file to filename
Searching word and character
/ ? - search the strings
t/ T -search for characters in the current line only
Set commands
:set nu - Displays lines with line numbers on the left side
:set ic - Ignores case when searching
:set ai - Sets autoindent
:set ro - Changes file type to "read only"
Text Buffers in VI
36 buffers for storing pieces of text, a general purpose buffer
“mdd -delete the current line and paste to buffer m
”mp – paste from the buffer m to the current position
Abbreviations
:ab st string- use st as an abbreviation instead of string
:una st – to remove the abbreviation
Running Commands
:! ls - if you want to check whether a file exists before you try to save your file to that filename
Press any key to return to the vi session
Recovering Your Work When Something Goes Wrong with Your Terminal
The VI editor edits a temporary copy of your file
After the editing is complete, or when you tell it to save, it puts the contents of the temporary copy into the original file.
If something goes wrong while you are editing your file, the VI editor will attempt to save whatever work you had in progress, and store it for later recovery.
vi -r newfile – recovering the newfile and we must save it.
* Screen-based editor
* Case sensitive
* Two modes
o Command mode- perform administrative tasks such as saving files, executing commands, moving the cursor, cutting (yanking) and pasting lines or words, and finding and replacing.
o Insert mode- insert text into the file
Starting the vi Editor
vi filename- creates a new file or open an existing file
vi -R filename- opens an existing file in read only mode
view filename- opens an existing file in read only mode
Inserting text
vi always opens in command mode.
i- insert text before the current cursor location
Esc – back into command mode.
I - Inserts text at the beginning of current line
a - Inserts text after current cursor location
A - Inserts text at the end of current line
o - Creates a new line for text entry below cursor location
O - Creates a new line for text entry above cursor location
Getting out of vi
:q -quit without saving
:wq / ZZ- quite while saving
:w- save the file
:w filename2- save the file by another name
:q!- enforce to quit without saving
Moving cursor in command mode
k – up one line
j - down one line
h - to the left one character one position
l- to the right one character one position
0/| -beginning of line
$ - end of line
:x – to the line number x
Deleting characters
x -Deletes the character under the cursor location
X - Deletes the character before the cursor location
dd- Deletes the line the cursor is on
2dd-Deletes 2 lines
D - Deletes from the cursor position to the end of the current line
Change commands
cc - Removes contents of the line, leaving you in insert mode
r - Replaces the character under the cursor. vi returns to command mode after the replacement is entered
s - Replaces the current character with the character you type. Afterward, you are left in insert mode
Copy and Paste Commands
yy- Copies the current line
p- Puts the copied text after the cursor
P- Puts the yanked text before the cursor
Advanced Commands
J - Join the current line with the next one. A count joins that many lines
<< - Shifts the current line to the left by one shift width
>> - Shifts the current line to the right by one shift width
~ - Switch the case of the character under the cursor
^G - Press CNTRL and G keys at the same time to show the current filename and the status
U- Restore the current line to the state it was in before the cursor entered the line
u - Undo the last change to the file. Typing 'u' again will re-do the change
:f filename - Renames current file to filename
Searching word and character
/ ? - search the strings
t/ T -search for characters in the current line only
Set commands
:set nu - Displays lines with line numbers on the left side
:set ic - Ignores case when searching
:set ai - Sets autoindent
:set ro - Changes file type to "read only"
Text Buffers in VI
36 buffers for storing pieces of text, a general purpose buffer
“mdd -delete the current line and paste to buffer m
”mp – paste from the buffer m to the current position
Abbreviations
:ab st string- use st as an abbreviation instead of string
:una st – to remove the abbreviation
Running Commands
:! ls - if you want to check whether a file exists before you try to save your file to that filename
Press any key to return to the vi session
Recovering Your Work When Something Goes Wrong with Your Terminal
The VI editor edits a temporary copy of your file
After the editing is complete, or when you tell it to save, it puts the contents of the temporary copy into the original file.
If something goes wrong while you are editing your file, the VI editor will attempt to save whatever work you had in progress, and store it for later recovery.
vi -r newfile – recovering the newfile and we must save it.
Thursday, January 6, 2011
JUnit
JUnit is a framework to implement testing in JAVA. We can start testing with few steps using JUnit. First we have to download the latest version of JUnit, extract the zip to a directory and add path to CLASSPATH environment variable. Here I describe basic steps to implement testing with JUnit.
1. Import junit.framework subdirectory.
import junit.framework.*;
2. Extend TestCase to your simple java class to provide the ability to define our test methods.
public class MyClass extends TestCase {
3. Implement the constructor with a string argument that passes the name to super constructor as below. Every test have a name. By implementing this constructor, we can view which test gives an error from overall test results.
public MyClass(String name) {
super(name);
}
4. Define our own test method. This method is a simple test method to check whether mytest variable equals to 2.
public void testMyClassMethod(){
int mytest=1;
assertEquals("Mytest must be 1", mytest,1);
}
1. Import junit.framework subdirectory.
import junit.framework.*;
2. Extend TestCase to your simple java class to provide the ability to define our test methods.
public class MyClass extends TestCase {
3. Implement the constructor with a string argument that passes the name to super constructor as below. Every test have a name. By implementing this constructor, we can view which test gives an error from overall test results.
public MyClass(String name) {
super(name);
}
4. Define our own test method. This method is a simple test method to check whether mytest variable equals to 2.
public void testMyClassMethod(){
int mytest=1;
assertEquals("Mytest must be 1", mytest,1);
}
Thursday, December 30, 2010
Intercepting Filter
Presentation-tier request handling mechanism receives different type of requests. They require various type of processing such as authentication checking, validation checking, modifying, auditing. Therefore, preprocessing and post processing of a client request is required. In the normal scenario, we can do this by conditional checks and with a invaild check, abort the request. But this is not a good solution because, we have to change the code according to the type of request. Therefore, the best solution is to add and remove components, these specific components complete specific filtering actions.
Therefore, when a client send a request, FilterManager manages the needed filters according to the order. It is the FilterChain with appropriate filters. It is an ordered collection of independent filters. The Filter chain coordinates their processing that are mapped to a target. The target is the resource that client requests.
Therefore, when a client send a request, FilterManager manages the needed filters according to the order. It is the FilterChain with appropriate filters. It is an ordered collection of independent filters. The Filter chain coordinates their processing that are mapped to a target. The target is the resource that client requests.
Sunday, December 26, 2010
Apache Maven-What is a POM?
The fundamental unit of work in Maven is POM, Project Object Model. It is a XML file containing the project and configuration details used by Maven to build the project. When executing a task, Maven looks for the POM in the current directory to get needed configuration information such as project dependencies, the plugins, goals and the build profiles. POM contains other information such as project version, description, developers and mailing lists.
The Super POM is Maven's default POM. All POMs we create extend the Super POM and Super POM is inherited by the POMs. Minimum requirements for a POM are the project root, modelVersion, groupId, artifactId, version. Here is a example of a POM file with minimum requirements.
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany.app</groupId>
<artifactId>my-app</artifactId>
<version>1</version>
</project>
If the configuration details are not specified, Maven will use their defaults. Here, with the minimum requirements, repositories are not defined. Therefore, when it is built, it will inherit the repositories configuration from Super POM.
If we want to add an another artifact to our project, my-app, it will be something like this.
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany.app</groupId>
<artifactId>my-module</artifactId>
<version>1</version>
</project>
If we want to make the my-app project the parent of newly created artifact, we have to edit the newly created artifact module's pom file as below to include the parent's section.
<project>
<parent>
<groupId>com.mycompany.app</groupId>
<artifactId>my-app</artifactId>
<version>1</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany.app</groupId>
<artifactId>my-module</artifactId>
<version>1</version>
</project>
The Super POM is Maven's default POM. All POMs we create extend the Super POM and Super POM is inherited by the POMs. Minimum requirements for a POM are the project root, modelVersion, groupId, artifactId, version. Here is a example of a POM file with minimum requirements.
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany.app</groupId>
<artifactId>my-app</artifactId>
<version>1</version>
</project>
If the configuration details are not specified, Maven will use their defaults. Here, with the minimum requirements, repositories are not defined. Therefore, when it is built, it will inherit the repositories configuration from Super POM.
If we want to add an another artifact to our project, my-app, it will be something like this.
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany.app</groupId>
<artifactId>my-module</artifactId>
<version>1</version>
</project>
If we want to make the my-app project the parent of newly created artifact, we have to edit the newly created artifact module's pom file as below to include the parent's section.
<project>
<parent>
<groupId>com.mycompany.app</groupId>
<artifactId>my-app</artifactId>
<version>1</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany.app</groupId>
<artifactId>my-module</artifactId>
<version>1</version>
</project>
Wednesday, December 22, 2010
EntityManager
EntityManager manages entities. The javax.persistence.EntityManager instances represent the entity manager. Each EntityManager instance is associated with a persistent context. A persistence context defines the scope under which particular entity instances are created, persisted, and removed and it is a set of managed entity instances that exist in a particular data source. The EntityManager interface defines the methods that are used to interact with the persistence context like creating and removing persistent entity instances, finding entities by the entity’s primary key, and allowing queries to be run on entities.
Container-Managed Entity Managers
EntityManager instance’s persistence context is automatically propagated by the container to all application components that use the EntityManager instance within a single Java Transaction Architecture (JTA) transaction. The Java EE container manages the life cycle of container-managed entity managers.
To obtain an EntityManager instance, inject the entity manager into the application component:
@PersistenceContext
EntityManager em;
Application-Managed Entity Managers
The persistence context is not propagated to application components, and the life cycle of EntityManager instances is managed by the application. Applications create EntityManager instances using the createEntityManager method of javax.persistence.EntityManagerFactory.
To obtain an EntityManager instance, you first must obtain an EntityManagerFactory instance by injecting it into the application component by means of the javax.persistence.PersistenceUnit annotation:
@PersistenceUnit
EntityManagerFactory emf;
EntityManager em = emf.createEntityManager();
The EntityManager.find method is used to look up entities in the data store by the entity’s primary key.
@PersistenceContext
EntityManager em;
public void enterOrder(int custID, Order newOrder) {
Customer cust = em.find(Customer.class, custID);
cust.getOrders().add(newOrder);
newOrder.setCustomer(cust);
}
Managing an Entity Instance’s Life Cycle
The four states of an entity instance are new, managed, detached and removed. New entity instances have no persistent identity and are not yet associated with a persistence context. Managed entity instances have a persistent identity and are associated with a persistence context. Detached entity instances have a persistent identify and are not currently associated with a persistence context. Removed entity instances have a persistent identity, are associated with a persistent context, and are scheduled for removal from the data store.
By invoking the persist method or by a cascading persist operation invoked from related entities that have the cascade=PERSIST or cascade=ALL elements set in the relationship annotation, new entity instances become managed and persistent. The entity’s data is stored to the database when the transaction associated with the persist operation is completed. Managed entity instances are removed by invoking the remove method, or by a cascading remove operation invoked from related entities that have the cascade=REMOVE or cascade=ALL elements set in the relationship annotation.
Creating Queries
The EntityManager.createQuery and EntityManager.createNamedQuery methods are used to query the data store using Java Persistence query language queries. The createQuery method is used to create dynamic queries.
public List findWithName(String name) {
return em.createQuery(
"SELECT c FROM Customer c WHERE c.name LIKE :custName")
.setParameter("custName", name)
.setMaxResults(10)
.getResultList();
}
The createNamedQuery method is used to create static queries.
@NamedQuery(
name="findAllCustomersWithName",
query="SELECT c FROM Customer c WHERE c.name LIKE :custName"
)
@PersistenceContext
public EntityManager em;
...
customers = em.createNamedQuery("findAllCustomersWithName")
.setParameter("custName", "Smith")
.getResultList();
Container-Managed Entity Managers
EntityManager instance’s persistence context is automatically propagated by the container to all application components that use the EntityManager instance within a single Java Transaction Architecture (JTA) transaction. The Java EE container manages the life cycle of container-managed entity managers.
To obtain an EntityManager instance, inject the entity manager into the application component:
@PersistenceContext
EntityManager em;
Application-Managed Entity Managers
The persistence context is not propagated to application components, and the life cycle of EntityManager instances is managed by the application. Applications create EntityManager instances using the createEntityManager method of javax.persistence.EntityManagerFactory.
To obtain an EntityManager instance, you first must obtain an EntityManagerFactory instance by injecting it into the application component by means of the javax.persistence.PersistenceUnit annotation:
@PersistenceUnit
EntityManagerFactory emf;
EntityManager em = emf.createEntityManager();
The EntityManager.find method is used to look up entities in the data store by the entity’s primary key.
@PersistenceContext
EntityManager em;
public void enterOrder(int custID, Order newOrder) {
Customer cust = em.find(Customer.class, custID);
cust.getOrders().add(newOrder);
newOrder.setCustomer(cust);
}
Managing an Entity Instance’s Life Cycle
The four states of an entity instance are new, managed, detached and removed. New entity instances have no persistent identity and are not yet associated with a persistence context. Managed entity instances have a persistent identity and are associated with a persistence context. Detached entity instances have a persistent identify and are not currently associated with a persistence context. Removed entity instances have a persistent identity, are associated with a persistent context, and are scheduled for removal from the data store.
By invoking the persist method or by a cascading persist operation invoked from related entities that have the cascade=PERSIST or cascade=ALL elements set in the relationship annotation, new entity instances become managed and persistent. The entity’s data is stored to the database when the transaction associated with the persist operation is completed. Managed entity instances are removed by invoking the remove method, or by a cascading remove operation invoked from related entities that have the cascade=REMOVE or cascade=ALL elements set in the relationship annotation.
Creating Queries
The EntityManager.createQuery and EntityManager.createNamedQuery methods are used to query the data store using Java Persistence query language queries. The createQuery method is used to create dynamic queries.
public List findWithName(String name) {
return em.createQuery(
"SELECT c FROM Customer c WHERE c.name LIKE :custName")
.setParameter("custName", name)
.setMaxResults(10)
.getResultList();
}
The createNamedQuery method is used to create static queries.
@NamedQuery(
name="findAllCustomersWithName",
query="SELECT c FROM Customer c WHERE c.name LIKE :custName"
)
@PersistenceContext
public EntityManager em;
...
customers = em.createNamedQuery("findAllCustomersWithName")
.setParameter("custName", "Smith")
.getResultList();
Log4j
Log4j is an open source project that allows the developers to control which log statements are output with arbitrary granularity. It is fully configurable at runtime using external configuration files. The advantages of the logging are providing a precise context about a run of the application, the generation of the logging output requires no human intervention, log output can be saved in persistent medium. The drawback of logging is slowing down the application.
Log4j has three main components. They are loggers, appenders and layouts. These three components are used to log messages according to message type and level and to control at run time how these messages are formatted and when they are reported. The advantage of logging API than System.out.println(); is it's ability to disable certain log statements while allowing others to print unhindered( logging space, that is, the space of all possible logging statements, is categorized according to some developer-chosen criteria ).
The root logger is the top of the logger hierarchy. It always exists and cannot be retrieved by name. Logger.getRootLogger method retrives the root of hierarchy. All other loggers are instantiated and retrieved with the class static Logger.getLogger method. Some methods in the logger class are stated below.
public void trace(Object message);
public void debug(Object message);
public void info(Object message);
public void warn(Object message);
public void error(Object message);
public void fatal(Object message);
public void log(Level l, Object message);
Loggers may be assigned levels. They are TRACE, DEBUG, INFO, WARN, ERROR and FATAL defined in the org.apache.log4j.level class. We can define our own level by subclassing the Level class. Root logger has an asigned level. If a logger is not assigned a level, it inherits from the ancestors. Logging requests are made by invoking one of the printing methods of a logger instance. These printing methods are debug, info, warn, error, fatal and log.By definition, the printing method determines the level of a logging request. A logging request is said to be enabled if its level is higher than or equal to the level of its logger. Otherwise, the request is said to be disabled. A logger without an assigned level will inherit one from the hierarchy. The order of the levels is DEBUG < INFO < WARN < ERROR < FATAL. Calling the getLogger method with the same name will always return a reference to the exact same logger object.
Appenders and Layouts
Log4j allows logging requests to print to multiple destinations. An output destination is called an appender. Currently, appenders exist for the console, files, GUI components, remote socket servers, JMS, NT Event Loggers, and remote UNIX Syslog daemons. The addAppender method adds an appender to a given logger. Each enabled logging request for a given logger will be forwarded to all the appenders in that logger as well as the appenders higher in the hierarchy.
Output format can be customized using a layout with an appender. The layout formats the logging request according to the user's wishes and an appender sends the formatted output to its destination.
PatternLayout with the conversion pattern "%r [%t] %-5p %c - %m%n" will output:176 [main] INFO org.foo.Bar - Located nearest gas station.
The first field is the number of milliseconds elapsed since the start of the program. The second field is the thread making the log request. The third field is the level of the log statement. The fourth field is the name of the logger associated with the log request. The text after the '-' is the message of the statement.
Log4j has three main components. They are loggers, appenders and layouts. These three components are used to log messages according to message type and level and to control at run time how these messages are formatted and when they are reported. The advantage of logging API than System.out.println(); is it's ability to disable certain log statements while allowing others to print unhindered( logging space, that is, the space of all possible logging statements, is categorized according to some developer-chosen criteria ).
The root logger is the top of the logger hierarchy. It always exists and cannot be retrieved by name. Logger.getRootLogger method retrives the root of hierarchy. All other loggers are instantiated and retrieved with the class static Logger.getLogger method. Some methods in the logger class are stated below.
public void trace(Object message);
public void debug(Object message);
public void info(Object message);
public void warn(Object message);
public void error(Object message);
public void fatal(Object message);
public void log(Level l, Object message);
Loggers may be assigned levels. They are TRACE, DEBUG, INFO, WARN, ERROR and FATAL defined in the org.apache.log4j.level class. We can define our own level by subclassing the Level class. Root logger has an asigned level. If a logger is not assigned a level, it inherits from the ancestors. Logging requests are made by invoking one of the printing methods of a logger instance. These printing methods are debug, info, warn, error, fatal and log.By definition, the printing method determines the level of a logging request. A logging request is said to be enabled if its level is higher than or equal to the level of its logger. Otherwise, the request is said to be disabled. A logger without an assigned level will inherit one from the hierarchy. The order of the levels is DEBUG < INFO < WARN < ERROR < FATAL. Calling the getLogger method with the same name will always return a reference to the exact same logger object.
Appenders and Layouts
Log4j allows logging requests to print to multiple destinations. An output destination is called an appender. Currently, appenders exist for the console, files, GUI components, remote socket servers, JMS, NT Event Loggers, and remote UNIX Syslog daemons. The addAppender method adds an appender to a given logger. Each enabled logging request for a given logger will be forwarded to all the appenders in that logger as well as the appenders higher in the hierarchy.
Output format can be customized using a layout with an appender. The layout formats the logging request according to the user's wishes and an appender sends the formatted output to its destination.
PatternLayout with the conversion pattern "%r [%t] %-5p %c - %m%n" will output:176 [main] INFO org.foo.Bar - Located nearest gas station.
The first field is the number of milliseconds elapsed since the start of the program. The second field is the thread making the log request. The third field is the level of the log statement. The fourth field is the name of the logger associated with the log request. The text after the '-' is the message of the statement.
Sunday, December 12, 2010
Hibernate
Hibernate is an Open Source persistence technology. Hibernate maps the Java classes to the database tables. It also provides the data query and retrieval facilities that significantly reduces the development time. It is most useful with object-oriented domain modes and business logic in the Java-based middle-tier. Hibernate allows transparent persistence that enables the applications to switch any database. Hibernate can be used in Java Swing applications, Java Servlet-based applications, or J2EE applications using EJB session beans.
Features of Hibernate
In Hibernate, Java classes represent the table in the database and then map the instance variable in the class with the columns in the stabase. Then Hibernate can perform the operations like select, insert, update and delete by automatically creating the quiries.
Hibernate architecture has three main components:
Features of Hibernate
- Hibernate provides full-featured query facilities: Hibernate Query Language, the newly enhanced Hibernate Criteria Query API, and enhanced support for queries expressed in the native SQL dialect of the database.
- Filters for working with temporal (historical), regional or permissioned data.
- Enhanced Criteria query API: with full support for projection/aggregation and subselects.
- Runtime performance monitoring: via JMX or local Java API, including a second-level cache browser.
- Hibernate is Scalable: Hibernate has high performance and due to its dual-layer architecture can be used in the clustered environments.
- Less Development Time: Hibernate reduces the development timings as it supports inheritance, polymorphism, composition and the Java Collection framework.
- Automatic Key Generation: Hibernate supports the automatic generation of primary key for your.
In Hibernate, Java classes represent the table in the database and then map the instance variable in the class with the columns in the stabase. Then Hibernate can perform the operations like select, insert, update and delete by automatically creating the quiries.
Hibernate architecture has three main components:
- Connection Management: provides efficient management of the database connections.
- Transaction management: provides the ability to the user to execute more than one database statements at a time.
- Object relational mapping: technique of mapping the data representation from an object model to a relational data model and is used to select, insert, update and delete the records form the underlying table. When we pass an object to a Session.save() method, Hibernate reads the state of the variables of that object and executes the necessary query.
Spring
Spring framework is an open source technology and helps to simplify the developed of enterprise applications in Java technologies.
Features of Spring Framework:
Spring Architecture
Spring is well-organized architecture consisting of seven modules. Modules in the Spring framework are:
1. Spring AOP
To provide declarative enterprise services, especially as a replacement for EJB declarative services.
To allow users to implement custom aspects, complementing their use of OOP with AOP
2. Spring ORM
The ORM package that is related to the database access, provides integration layers for popular object-relational mapping APIs, including JDO, Hibernate and iBatis.
3. Spring Web
The Spring Web module is part of Spring’s web application development stack, which includes Spring MVC.
4. Spring DAO
The DAO (Data Access Object) support in Spring is primarily for standardizing the data access work using the technologies like JDBC, Hibernate or JDO.
5. Spring Context
This package builds on the beans package to add support for message sources and for the Observer design pattern, and the ability for application objects to obtain resources using a consistent API.
6. Spring Web MVC
This is the Module which provides the MVC implementations for the web applications.
7. Spring Core
This component provides the Dependency Injection features. The BeanFactory provides a factory pattern which separates the dependencies like initialization, creation and access of the objects from your actual program logic
Two way to configure Spring IOC container
a) xml file: The bean configuration is defined in xml file and then instruct the Spring to use the xml file to configure the beans.
b) Annotation: The @configuration spring annotation can also be used to configure the Spring IOC container. Here programmer add the @configuration to the Java class and this class is considered as special configuration class. The @Bean tag is used to define the bean, and the Spring framework executes the method and then register the object returned. By default the name of the method is used as the bean name.
XML Bean-Injection
InjectClass.java
class InjectClass {
private String name;
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return String.format("Name: " , this.name);
}
}
InjectClass is the java class. It has overided the toString() method.
XML file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="mybean" class="InjectClass"
p:name="XML Bean-Injection">
</beans>
xmlns:p="http://www.springframework.org/schema/p":-Namespace:"p" that cannot be validated.
<bean id="mybean" class="InjectClass">:- Here "InjectClass" is the name of the bean class which would be referred in the xml file with the id "mybean".
The xml file declares the spring bean "mybean" . The <bean .../> tag is used to declare a bean in the xml file. The xml file is used to configure the spring run-time environment. Spring framework manages the beans in our program.
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
public class Main {
public static void main(String[] args) {
XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource(
"context.xml"));
InjectClass demo = (InjectClass) beanFactory.getBean("mybean");
System.out.println(demo);
}
}
XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("context.xml")): creates an instance of the XmlBeanFactory which is used to read bean definition from an XML document
new ClassPathResource("context.xml"):-Creates a new ClassPathResource for ClassLoader .Here the context.xml is the file which is to be loaded.
Features of Spring Framework:
- Transaction Management: A generic abstraction layer for transaction management allows the developer to add the pluggable transaction managers, and making it easy to demarcate transactions without dealing with low-level issues.
- JDBC Exception Handling: The JDBC abstraction layer of the Spring offers a meaningful exception hierarchy, which simplifies the error handling strategy
- Integration with Hibernate, JDO, and iBATIS: Spring provides best Integration services with Hibernate, JDO and iBATIS.
- AOP Framework: Spring is best AOP framework
- MVC Framework: Spring comes with MVC web application framework, built on core Spring functionality.
Spring Architecture
Spring is well-organized architecture consisting of seven modules. Modules in the Spring framework are:
1. Spring AOP
To provide declarative enterprise services, especially as a replacement for EJB declarative services.
To allow users to implement custom aspects, complementing their use of OOP with AOP
2. Spring ORM
The ORM package that is related to the database access, provides integration layers for popular object-relational mapping APIs, including JDO, Hibernate and iBatis.
3. Spring Web
The Spring Web module is part of Spring’s web application development stack, which includes Spring MVC.
4. Spring DAO
The DAO (Data Access Object) support in Spring is primarily for standardizing the data access work using the technologies like JDBC, Hibernate or JDO.
5. Spring Context
This package builds on the beans package to add support for message sources and for the Observer design pattern, and the ability for application objects to obtain resources using a consistent API.
6. Spring Web MVC
This is the Module which provides the MVC implementations for the web applications.
7. Spring Core
This component provides the Dependency Injection features. The BeanFactory provides a factory pattern which separates the dependencies like initialization, creation and access of the objects from your actual program logic
Two way to configure Spring IOC container
a) xml file: The bean configuration is defined in xml file and then instruct the Spring to use the xml file to configure the beans.
b) Annotation: The @configuration spring annotation can also be used to configure the Spring IOC container. Here programmer add the @configuration to the Java class and this class is considered as special configuration class. The @Bean tag is used to define the bean, and the Spring framework executes the method and then register the object returned. By default the name of the method is used as the bean name.
XML Bean-Injection
InjectClass.java
class InjectClass {
private String name;
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return String.format("Name: " , this.name);
}
}
InjectClass is the java class. It has overided the toString() method.
XML file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="mybean" class="InjectClass"
p:name="XML Bean-Injection">
</beans>
xmlns:p="http://www.springframework.org/schema/p":-Namespace:"p" that cannot be validated.
<bean id="mybean" class="InjectClass">:- Here "InjectClass" is the name of the bean class which would be referred in the xml file with the id "mybean".
The xml file declares the spring bean "mybean" . The <bean .../> tag is used to declare a bean in the xml file. The xml file is used to configure the spring run-time environment. Spring framework manages the beans in our program.
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
public class Main {
public static void main(String[] args) {
XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource(
"context.xml"));
InjectClass demo = (InjectClass) beanFactory.getBean("mybean");
System.out.println(demo);
}
}
XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("context.xml")): creates an instance of the XmlBeanFactory which is used to read bean definition from an XML document
new ClassPathResource("context.xml"):-Creates a new ClassPathResource for ClassLoader .Here the context.xml is the file which is to be loaded.
Friday, December 10, 2010
A start to Apache Camel
Camel is an open-source, Java-based project that helps the user to implement many of the design patterns in the Enterprise Integration Patterns book. When we talk about the the term endpoint, in client-server communication, the client is one end point and the server is another endpoint. An endpoint might refer to an address, such as a host:port pair for TCP-based communication, or it might refer to a software entity that is contactable at that address.
Some examples of the Camel-supported endpoint technologies are JMS queue, web service, file, FTP server, email address, POJO (plain old Java object).
In camel based applications, endpoints are created and connected with routes. Camel defines a Java interface called Endpoint. Each Camel-supported endpoint has a class that implements this Endpoint interface.
A CamelContext object represents the Camel runtime system. You typically have one CamelContext object in an application. After creating a CamelContext object, we can add end points and routes to connect the end points.
Invoking the start() operation on the CamelContext object, starts Camel-internal threads that are used to process the sending, receiving and processing of messages in the endpoints.Invoke the stop() operation on the CamelContext object stops all the endpoints and Camel-internal threads. CamelTemplate class is a thin wrapper around the CamelContext class. It has methods that send a Message or Exchange to an endpoint. Therefore, messages can be sent to source endpoints, messages will move along routers.
Components are used to create the endpoints. As an example, if we take JmsComponent class(implements Component), JmsComponent.createEndpoint() creates an instance of the JmsEndpoint class (which implements the Endpoint interface). In the application-level, CamelContext.getEndpoint() finds the desired Component object and then invokes createEndpoint() on it.
myCamelContext.getEndpoint("pop3://john.smith@mailserv.example.com?password=myPassword");
The parameter to getEndpoint is a URI. URI prefix(the part before :) is Component. CamelContext object maintains a mapping from names of components(pop3) to Component objects. CamelContext object invokes createEndpoint("pop3://john.smith@mailserv.example.com?password=myPassword") on that MailComponent object. The createEndpoint() operation splits the URI into its component parts and uses these parts to create and configure an Endpoint object.
Message,Exchange and Processor
Message interface is an abstraction for a single message(request, reply or exception message). There are concrete classes that implement Message interface for each Camel supported communication technologies. The Exchange interface is an abstraction for an exchange of messages, that is, a request message and its corresponding reply or exception message. In Camel terminology, the request, reply and exception messages are called in, out and fault messages. There are also concrete classes that implement the Exchange interface for each Camel-supported communications technology.
The processor interface represents the process of a message. The classses that implement Processor interface provides support for a design pattern. For an example, ChoiceProcessor implements the message router pattern, FilterProcessor class which discards messages that do not satisfy a stated condition.
Routes, RouteBuilders and Java DSL
A route is the step-by-step movement of a Message from an input queue, through decision making (such as filters and routers) to a destination queue(if any). Camel provides two ways for an application developer to specify routes, XML file and Java DSL (domain-specific language). Java DSL is a class library that looks like DSL with JAVA
Some examples of the Camel-supported endpoint technologies are JMS queue, web service, file, FTP server, email address, POJO (plain old Java object).
In camel based applications, endpoints are created and connected with routes. Camel defines a Java interface called Endpoint. Each Camel-supported endpoint has a class that implements this Endpoint interface.
A CamelContext object represents the Camel runtime system. You typically have one CamelContext object in an application. After creating a CamelContext object, we can add end points and routes to connect the end points.
Invoking the start() operation on the CamelContext object, starts Camel-internal threads that are used to process the sending, receiving and processing of messages in the endpoints.Invoke the stop() operation on the CamelContext object stops all the endpoints and Camel-internal threads. CamelTemplate class is a thin wrapper around the CamelContext class. It has methods that send a Message or Exchange to an endpoint. Therefore, messages can be sent to source endpoints, messages will move along routers.
Components are used to create the endpoints. As an example, if we take JmsComponent class(implements Component), JmsComponent.createEndpoint() creates an instance of the JmsEndpoint class (which implements the Endpoint interface). In the application-level, CamelContext.getEndpoint() finds the desired Component object and then invokes createEndpoint() on it.
myCamelContext.getEndpoint("pop3://john.smith@mailserv.example.com?password=myPassword");
The parameter to getEndpoint is a URI. URI prefix(the part before :) is Component. CamelContext object maintains a mapping from names of components(pop3) to Component objects. CamelContext object invokes createEndpoint("pop3://john.smith@mailserv.example.com?password=myPassword") on that MailComponent object. The createEndpoint() operation splits the URI into its component parts and uses these parts to create and configure an Endpoint object.
Message,Exchange and Processor
Message interface is an abstraction for a single message(request, reply or exception message). There are concrete classes that implement Message interface for each Camel supported communication technologies. The Exchange interface is an abstraction for an exchange of messages, that is, a request message and its corresponding reply or exception message. In Camel terminology, the request, reply and exception messages are called in, out and fault messages. There are also concrete classes that implement the Exchange interface for each Camel-supported communications technology.
The processor interface represents the process of a message. The classses that implement Processor interface provides support for a design pattern. For an example, ChoiceProcessor implements the message router pattern, FilterProcessor class which discards messages that do not satisfy a stated condition.
Routes, RouteBuilders and Java DSL
A route is the step-by-step movement of a Message from an input queue, through decision making (such as filters and routers) to a destination queue(if any). Camel provides two ways for an application developer to specify routes, XML file and Java DSL (domain-specific language). Java DSL is a class library that looks like DSL with JAVA
Wednesday, December 8, 2010
Java Concurrency with Newly Added Features in JavaSE 5
Java concurrency helps developers to work with multi-threaded programs using features like Thread, synchronized and volatile. Threads communicate by calling a method of another thread. Some thread coordination methods are start, join and interrupt. A deadlock occurs when there is more than one thread, each waiting for the resource held by another. Starvation occurs when a thread holds a lock when some other starve without any progress. Wait/notify methods are used when one thread needs to signal when other thread waits till the condition is met.
A race condition occurs when more than one thread is performing actions on shared resources and several outcomes can exist with the order of the actions from each thread. Therefore, locking establishes the guarantee of the orderings. The monitor in every object provide mutual exclusion access to critical sections of code. Critical section is specified by marking as synchronized in a method or code block. Only one thread is allowed to enter the critical section for a particular monitor. Other threads have to wait for the monitor to be released.
java.util.concurrent.locks packages has a standard Lock interface. ReentrantLock implementation dublicated the functionality of the synchronized keyword with functionlity to obtain information about the state of lock. ReadWriteLock interface and ReentrantReadWrite Lock implementation define pair of locks for reading and writing. volatile modifier marked in a field indicate that the changes to that field must be seen by all subsequent reads by other threads.
java.util.concurrent package inculdes data structures designed for concurrent use. Use of these data structures gives better performances than using a synchoronized wrapper around an unsynchronized collection. As an example, CopyOnWriteArrayList is a thread-safe ArrayList where each modification of the data structure results in a new internal copy of the data. Queue acts as a "first in first out(FIFO)" adding elements in one end and removing from other end. BlockingQueue interface extends Queue and provide additional functionality how to handle the scenario where a queue may be full. Deque supports adding and removing from both ends, not adding from one end and removing from other end.
There are several classes for multi-thread communication such as CyclicBarrier, CountDownLatch, Semaphore and Exchanger. In task execution using a pool of workers, Executor and more ExecutorService interfaces define the contract for a component that can execute tasks.
A race condition occurs when more than one thread is performing actions on shared resources and several outcomes can exist with the order of the actions from each thread. Therefore, locking establishes the guarantee of the orderings. The monitor in every object provide mutual exclusion access to critical sections of code. Critical section is specified by marking as synchronized in a method or code block. Only one thread is allowed to enter the critical section for a particular monitor. Other threads have to wait for the monitor to be released.
java.util.concurrent.locks packages has a standard Lock interface. ReentrantLock implementation dublicated the functionality of the synchronized keyword with functionlity to obtain information about the state of lock. ReadWriteLock interface and ReentrantReadWrite Lock implementation define pair of locks for reading and writing. volatile modifier marked in a field indicate that the changes to that field must be seen by all subsequent reads by other threads.
java.util.concurrent package inculdes data structures designed for concurrent use. Use of these data structures gives better performances than using a synchoronized wrapper around an unsynchronized collection. As an example, CopyOnWriteArrayList is a thread-safe ArrayList where each modification of the data structure results in a new internal copy of the data. Queue acts as a "first in first out(FIFO)" adding elements in one end and removing from other end. BlockingQueue interface extends Queue and provide additional functionality how to handle the scenario where a queue may be full. Deque supports adding and removing from both ends, not adding from one end and removing from other end.
There are several classes for multi-thread communication such as CyclicBarrier, CountDownLatch, Semaphore and Exchanger. In task execution using a pool of workers, Executor and more ExecutorService interfaces define the contract for a component that can execute tasks.
Subscribe to:
Posts (Atom)