Thursday 12 December 2013

40:Thread Synchronization

Learning Objectives
After completing this session, you will be able to:
‰  Describe Thread Synchronization
‰  Explain lifecycle of threads
‰  Identify wait() method and notify() method of the Object class
Race Condition and How to Solve it
‰  Race conditions occur when multiple, asynchronously executing threads access the
same object (called a shared resource) returning unexpected (wrong) results.
‰  Example: Threads often need to share a common resource that is a file, with one
thread reading from the file while another thread writes to the file.
‰  They can be avoided by synchronizing the threads, which access the shared resource.
An Unsynchronized Example
1 class TwoStrings {
2 static void print(String str1, String str2) {
3 System.out.print(str1);
4 try {
5 Thread.sleep(500);
6 } catch (InterruptedException ie) {
7 }
8 System.out.println(str2);
9 }
10 }
11
12 class PrintStringsThread implements Runnable {
13 Thread thread;
14 String str1, str2;
15 PrintStringsThread(String str1, String str2) {
16 this.str1 = str1;
17 this.str2 = str2;
18 thread = new Thread(this);
19 thread.start();
20 }
21 public void run() {
22 TwoStrings.print(str1, str2);
23 }
24 }
25
26 class TestThread {
27 public static void main(String args[]) {
28 new PrintStringsThread("Hello ", "there.");
29 new PrintStringsThread("How are ", "you?");
30 new PrintStringsThread("Thank you ",
31 "very much!");
32 }
33 }
Sample output:
Hello How are Thank you there.
you?
very much!
Synchronization: Locking an Object
A thread is synchronized by becoming an owner of the monitor of the object: Consider it as locking
an object
A thread becomes the owner of the monitor of the object in one of following ways:
‰  Option 1: Use synchronized method
‰  Option 2: Use synchronized statement on a common object
Option 1: Use Synchronized Method
1 class TwoStrings {
2 synchronized static void print(String str1,
3 String str2) {
4 System.out.print(str1);
5 try {
6 Thread.sleep(500);
7 } catch (InterruptedException ie) {
8 }
9 System.out.println(str2);
10 }
11 }
12
13 class PrintStringsThread implements Runnable {
14 Thread thread;
15 String str1, str2;
16 PrintStringsThread(String str1, String str2) {
17 this.str1 = str1;
18 this.str2 = str2;
19 thread = new Thread(this);
20 thread.start();
21 }
22 public void run() {
23 TwoStrings.print(str1, str2);
24 }
25 }
26
27 class TestThread {
28 public static void main(String args[]) {
29 new PrintStringsThread("Hello ", "there.");
30 new PrintStringsThread("How are ", "you?");
31 new PrintStringsThread("Thank you ",
32 "very much!");
33 }
34 }
Option 1: Executing Synchronized Method
Sample output:
Hello there.
How are you?
Thank you very much!
Option 2: Use Synchronized Statement on a Common Object
1 class TwoStrings {
2 static void print(String str1, String str2) {
3 System.out.print(str1);
4 try {
5 Thread.sleep(500);
6 } catch (InterruptedException ie) {
7 }
8 System.out.println(str2);
9 }
10 }
11
12 class PrintStringsThread implements Runnable {
13 Thread thread;
14 String str1, str2;
15 TwoStrings ts;
16 PrintStringsThread(String str1, String str2,
17 TwoStrings ts) {
18 this.str1 = str1;
19 this.str2 = str2;
20 this.ts = ts;
21 thread = new Thread(this);
22 thread.start();
23 }
24
25 public void run() {
26 synchronized (ts) {
27 ts.print(str1, str2);
28 }
29 }
30 }
31 class TestThread {
32 public static void main(String args[]) {
33 TwoStrings ts = new TwoStrings();
34 new PrintStringsThread("Hello ", "there.", ts);
35 new PrintStringsThread("How are ", "you?", ts);
36 new PrintStringsThread("Thank you ",
37 "very much!", ts);
38 }
39 }
wait() Method of Object Class
‰  wait() method causes a thread to release the lock it is holding on an object allowing
another thread to run.
‰  wait() method is defined in the Object class.
‰  wait() can only be invoked from within synchronized code.
‰  It should always be wrapped in a try block as it throws IOException.
‰  wait() can only be invoked by the thread that owns the lock on the object.
‰  When wait() is called, the thread becomes disabled for scheduling and lies dormant
until one of the four things occur:
‰  Another thread invokes the notify() method for this object and the scheduler arbitrarily
chooses to run the thread.
‰  Another thread invokes the notifyAll() method for this object.
‰  Another thread interrupts this thread.
‰  The specified wait() time elapses.
‰  When one of the earlier occurs, the thread becomes re-available to the Thread
scheduler and competes for a lock on the object
‰  Once it regains the lock on the object, everything resumes as if no suspension had
occurred.
notify() Method
‰  notify() method wakes up a single thread thatis waiting on the monitor of this object:
‰  If any threads are waiting on this object, then one of them is chosen to be awakened.
‰  The choice is arbitrary and occurs at the discretion of the implementation.
‰  notify() method can only be used within synchronized code.
‰  The awakened thread will not be able to proceed until the current thread relinquishes
the lock on this object.
Try It Out:-
Problem Statement:
Write a program that illustrates the usage of synchronized statement in thread synchronization.
Code:
class ThreadSynchronizedStmtApp extends Thread {
static String message[] = { "Java", "is", "hot,", "aromatic,",
"and",
"invigorating." };
public static void main(String args[]) {
ThreadSynchronizedStmtApp thread1 = new
ThreadSynchronizedStmtApp("thread1: ");
ThreadSynchronizedStmtApp thread2 = new
ThreadSynchronizedStmtApp("thread2: ");
thread1.start();
thread2.start();
boolean thread1IsAlive = true;
boolean thread2IsAlive = true;
How It Works:
‰  The synchronized statement is similar to a synchronized method in that. It is used to
acquire a lock on an object before performing an action.
‰  The synchronized statement differs from a synchronized method in that. It can be used
with the lock of any object. The synchronized method can only be used with the lock of
object or class.
‰  It also differs in a way that it applies toa statement block, rather than an entire
method.
‰  The syntax of the synchronized statement is as follows:
synchronized (object) {
statement(s)
}
‰  The statements enclosed by the braces are only executed when the current thread
acquires the lock for the object or class enclosed by parentheses.
Tips and Tricks:
Can you reuse a Thread object? Can you give it a newjob to do and then restart it by calling start()
again?
Solution:
‰  No. Once the run() method of a thread has completed, the thread can never be
restarted. In fact, at that point the thread moves into the dead state. In the dead state,
the thread has finished its run() method and can never be restarted. The Thread object
might still be on the heap, as a living object that you can call other methods on (if
appropriate), but the Thread object has permanently lost its ‘threadness’. In other
words, the Thread object is no longer a thread. It is just an object, at that point, like all
other objects.
‰  But, there are design patterns, for making a pool of threads that you can keep using to
perform different jobs. But you do not do it by restarting a dead thread.
Summary
‰  Synchronized methods prevent more than one thread from accessing an object’s
critical method code simultaneously.
‰  You can use the synchronized keyword asa method modifier, or to start a
synchronized block of code.
‰  To synchronize a block of code, you mustspecify an argument that is the object
whose lock you want to synchronize on.
‰  While only one thread can be accessing synchronized code of particular instance,
multiple threads can still access the same object’s unsynchronized code.
‰  Static methods can be synchronized, using the lock from the java.lang.Class instance
representing that class.

Monday 19 August 2013

Garbage Collection - 48

Learning Objectives
After completing this session, you will be able to:
‰  Define Garbage Collector
‰  Explain the GC Designs
‰  Identify the Memory Leaks
Garbage Collector
The Garbage Collector runs in a thread in the JVM. When the free memory drops under a
threshold the GC begins to run to eliminate unneeded objects. Exactly when it runs and for how
long, however, cannot be controlled by the user program.
Important Facts About GC
‰  GC is unpredictable in nature, and in fact, causes serious problems for Real Time (RT)
applications of Java.
‰  The JVM does not actually require a GC and in some special situations, the GC is
simply turned off or left out. In that case, the program must itself make sure that it
does not run out of memory.
What Does a GC Perform?
‰  If a section of memory earlier used by an object is no longer referenced by any
variable, then the Garbage Collector (GC) will release this memory for re-use by new
objects. This takes place automatically without any input from the user program.
‰  There are no heap commands such malloc() and free() functions in C needed to
allocate or de-allocate memory buffers.
‰  Java does use a similar "new" operator as in C++ for creating objects but has no
"delete" operator.
Overview of GC Designs
The JVM Specification does not in fact specify very much about the GC. It leaves considerable
room for variation in implementation. Research continues in the computer science community for
fast and efficient GC algorithms. A GC must meet a number of difficult challenges:
‰  Recognize and eliminate dead (unreferenced) objects from the heap
‰  Keep the heap from becoming so fragmented that new objects do not easily fit
‰  Minimize the processing time taken away from the application
‰  Recognize circular cases where dead objects (that is, objects are no longer accessible
from the live thread processes or from static references) referencing each other and
so might give them the appearance of life
Some of the Common Garbage Collector Designs
Some of the common GC designs are:
‰  Copying Collector:
‰  Scan through all references to determine which objects are live (referenced) and copy
them to one half of the heap
‰  When finished, free up the old half
‰  Restart the application
‰  Repeat when free memory drops under a threshold
‰  Mark and Sweep:Scan through all references and mark the objects that are live
‰  Free up the areas occupied by dead objects
‰  Mark and Compact: Similar to Mark and Sweep except after the marking phase, the
live objects are copied to a free area and all of the area earlier occupied by objects is
freed up
Generational:
‰  Most objects in most programs only last for a brief time.
‰  It is more efficient to concentrate on freeing up memory from the short-lived objects
and spend as little time as possible checking on old but stable objects.
‰  The generational GC creates at least two sub-heap areas with one for short-lived
objects and the other for old objects.
‰  A Mark and Sweep or other GC algorithm would work on the short-lived heap.
‰  Those objects that last beyond a few cycles are moved to the long-lived heap, which is
only checked occasionally.
‰  These types of algorithms (as discussed in earlier slides) must interrupt the application
threads and complete their job before returning control.
‰  There are some algorithms that work in an incremental approach, rather than
completing a full clean-up at one go, and thus interfere less with the program.
Memory Leaks
‰  Memory leak refers to the loss of free memory in the heap to unusable data as a
program runs.
‰  This can lead to inefficient memory utilization and eventually to a crash of the program
when no free memory remains.
‰  Even with the garbage collector, memory leaks can still occur in Java.
Examples for Memory Leaks
Examples of situations that create memory leaks include:
‰  Maintaining references to unneeded objects: For example, a method might create
temporary objects in the first section ofthe method and then go on to do other tasks
such as a loop in which the temporary objects are no longer needed.
‰  If references to the temporary objects remain, then the objects will not be collected
and take up memory. In such cases the references should explicitly be set to null.
Waiting for finalizer:
‰  A class can override the finalize() method and use it to do clean up tasks before the
object is reclaimed by the GC.
‰  However, there is no way to know when the finalizer will be called and if a lot of
objects with finalizers are waiting for their final invocation, a lot of memory might be
used up.
‰  Generally, it is recommended to avoid application of the finalize() method and instead
create a clean up method that you call explicitly when the object is no longer needed.
Try It Out
Problem Statement:
Write a program that illustrates the working of Garbage Collector.
Code:
public class GarbageDemo {
Garbage g;
int max;
public static void main(String[] args) {
int n = 15;
if (args.length > 0)
n = (new Integer(args[0])).intValue();
GarbageDemo app = new GarbageDemo(n);
app.run();
}
public GarbageDemo(int n) {
max = n;
}
Summary
‰  In Java, garbage collection (GC) provides automated memory management.
‰  The purpose of GC is to delete objects that can’t be reached.
‰  Only the JVM decides when to run the GC, you can only suggest it.
‰  You can’t know the GC algorithm for sure.
‰  Objects must be considered eligiblebefore they can be garbage collected.
‰  An object is eligible when no live thread can reach it.
‰  To reach an object, you must have a live, reachable reference to that object.
Test Your Understanding
1.State true or false for the following:
a)Garbage Collection is a mechanism for reclaiming memory from objects that are
no longer in application, making the memory available for new objects.
b)An object being no longer in application means that it still can be referenced by
any ‘active’ part of the program.
c)Garbage Collection runs in a high priority thread. It will never kick in when memory
is too low.

GC Performance Metrics-49

Learning Objectives
After completing this session, you will be able to:
‰  Describe the important GC Performance Metrics
‰  Identify the types of Garbage Collectors
Important GC Performance Metrics
‰  Throughput:The percentage of total time not spent in garbage collection is
considered over long periods of time.
‰  Pause time:The length of time during which application execution is stopped while
garbage collection is being performed is called the pause time.
‰  Application Requirement:Different applications have different requirements:
‰  Higher throughput is more important for Web application:Pauses during Garbage
Collection may be tolerable, or simply obscured by network latencies.
‰  Shorter pause time is more important to an interactive graphics application
Types of Garbage Collector
The types of Garbage Collector are:
‰  Serial Collector
‰  Parallel Collector
‰  Parallel Compacting Collector
‰  Concurrent Mark-Sweep (CMS) Collector
Serial Collector
‰  Serial Collector is used for most applications that are running on client-style machines,
which do not have low pause time requirement.
‰  Serial Collector is the default for client-style machines in Java SE 5.
‰  Serial Collector can be explicitly requested with XX:+UseSerialGC.
Parallel Collector
‰  Parallel Collector is also known as Throughput Collector.
‰  This is applied for Java applications, which run on machines with a lot of physical
memory and multiple CPUs and do not have low pause time requirement:
‰  Infrequent but potentially long old generation GC can still occur
‰  Examples: Batch applications, billing, payroll, scientific computing, and so on
‰  Parallel Collector can be explicitly requested with XX:+UseParallelGC.
Parallel Compact Collector
‰  Parallel Compact Collector is used for Javaapplications, which run on machines with
a lot of physical memory and multiple CPUs and do have low pause time requirement.
Parallel operations of old generation collection reduces pause time.
‰  Parallel Compact Collector can be explicitly requested with XX:+UseParallelOldGC.
Concurrent Mark Sweep Collector
Concurrent Mark Sweep Collector is used when an application needs shorter pause time and can
afford to share processor resources with GC when application is running
Applications with relatively large set of long-lived data (a large old generation) and run multi-CPU
machines
Example:Web server
Can be explicitly requested with:
‰  -XX:+UseConcMarkSweepGC
‰  -XX:ParallelCMSThreads=<n>
Scheduling of collection handled by GC:
Based on statistics in JVM
Occupancy level of tenured generation:
‰  -XX:CMSTriggerRatio
‰  -XX:CMSInitiatingOccupancyFraction
CMS Collector in Incremental Mode
‰  CMS Collector can be used in a mode in which the concurrent phases are done
incrementally:
‰  Meant to lesson the impact of long concurrent phases by periodically stopping the
concurrent phase to yield back processing to the application
‰  Can be explicitly requested with XX:+CMSIncrementalMode.
Other Incremental CMS Options
Other incremental CMS options are:
‰  -XX:CMSIncrementalDutyCycle=<n%> (default: 50)
‰  -XX:CMSIncrementalDutyCycleMin=<n%> (default: 10)
‰  -XX:+CMSIncrementalPacing (default: true)
DutyCycle of 10 and DutyCycleMin of0 can help certain applications
Tips and Tricks:
Provide some key points on Garbage Collection.
Solution:
‰  It is not possible to force Garbage Collection. Invoking System.gc may start garbage
process.
‰  Circular references do not prevent objects from being garbage collected.
‰  All objects have a finalize() method. It isinherited from the Object class.
‰  finalize() method is used to release system resources other than memory.
‰  finalize() method is called only once for an object. If an exception is thrown in finalize
(), then the object is still eligible for Garbage Collection (at the discretion of gc).
‰  gc keeps track of unreachable objects and garbage-collects them, but an unreachable
object can become reachable again by letting know other objects of its existence from
its finalize() method (when called by gc). This ‘resurrection’ can be done only once,
since finalize() is called only once for an object.
‰  finalize() can be called explicitly, but itdoes not garbage collect the object.
Summary
‰  Java applications can run out of memory.
‰  Islands of objects can be garbage collected, even though they refer to each other.
‰  Request garbage collection with System.gc(); (recommended).
‰  Class Object has a finalize() method.
‰  The finalize() method is guaranteed to run once and only once before the garbage
collector deletes an object.
‰  The garbage collector makes no guarantees, fianlize() may never run.
‰  You can uneligibilize an object for GC from within finalize().
Test Your Understanding
1.State true or false for the following:
a)There is no guarantee on the order in which the objects will be garbage collected
or on the order in which the finalizers are called. Therefore the program should not
make any decisions based on this assumption.

Friday 16 August 2013

Annotation- 50

Learning Objectives
After completing this session, you will be able to:
‰  Define Annotation
‰  Explain the importance of Annotation
‰  Identify Built-in Annotations
How Annotations are Used?
Annotations are used to affect the way programs are treated by tools and libraries.
Annotations are used by tools to produce derived files:
Tools:Compiler, IDE, and Run-time tools
Derived files:New Java code, deployment descriptor, and class files
Ad-hoc Annotation-like Examples in pre-J2SE 5.0 Platform
Ad-hoc Annotation-like examples in pre-J2SE 5.0 platform:
‰  Transient
‰  Serializable interface
‰  @deprecated
‰  javadoc comments
‰  Xdoclet
J2SE 5.0 Annotation provides a standard, general purpose, and more powerful annotation
scheme.
Need of Annotation
Annotation enables “declarative programming” style:
‰  Less coding because tool will generate the boiler plate code from annotations in the
source code
‰  Easier to change
Annotation eliminates the need for maintaining "side files" that must be kept up to date with
changes in source files:
‰  Information is kept in the source file
‰  (example) Eliminate the need of deployment descriptor
Built-in Annotations
Java defines seven built-in annotations.
The following four are imported from java.lang.annotation:
‰  @Retention
‰  @Documented
‰  @Target
‰  @Inherited
The following three are included in java.lang:
‰  @Override
‰  @Deprecated
‰  @SuppressWarnings
Annotation Retention Policy
‰  A retention policy determines at whatpoint an annotation is discarded.
‰  Java defines three such policies of SOURCE, CLASS, and RUNTIME.
‰  The earlier policies are encapsulated withinthe java.lang.annotation.RetentionPolicy
enumeration.
‰  An annotation with a retention policy of SOURCE is retained only in the source file and
is discarded during compilation.
‰  An annotation with a retention policy of CLASS is stored in the .class file during
compilation. However, it is not available through the JVM during run time.
‰  An annotation with a retention policy of RUNTIME is stored in the .class file during
compilation and is available through the JVM during run time.
‰  RUNTIME retention offers the greatest annotation persistence.
@Retention
‰  @Retention is designed to be used only as an annotation to another annotation.
‰  Its general form is as follows:
@Retention(retention-policy)
‰  Here, retention-policy must be one of the earlier discussed enumeration constants. If
no retention policy is specified for an annotation, then the default policy of CLASS is
used.
‰  The following example uses @Retention tospecify the RUNTIME retention policy.
Thus, the following annotation (MyAnno) will be available to the JVM during program
execution.
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnno {
String str();
int val();
}
@Documented
‰  The @Documented annotation is a marker interface, which tells a tool that an
annotation is to be documented.
‰  It is designed to be used only as an annotation to an annotation declaration.
@Target
‰  The @Target annotation specifies the types of declarations to which an annotation
can be applied.
‰  It is designed to be used only as an annotation to another annotation.
‰  @Target takes one argument, which must be a constant from the ElementType
enumeration. This argument specifies the types of declarations to which the
annotation can be applied.
The following table shows the constants and the type of declaration to which they correspond:
Target Constant  Annotation Can Be Applied To
ANNOTATION_TYPE  Another annotation
CONSTRUCTOR  Constructor
FIELD  Field
LOCAL_VARIABLE  Local variable
METHOD  Method
PACKAGE  Package
PARAMETER  Parameter
TYPE  Class, interface, or enumeration
‰  You can specify one or more of the values (as shown in the earlier slide) in a @Target
annotation.
‰  To specify multiple values, you must specify them within a braces-delimited list.
‰  For example, to specify that an annotation applies only to fields and local variables,
you can use this @Target annotation:
@Target( { ElementType.FIELD,ElementType.LOCAL_VARIABLE } )
@Inherited
‰  @Inherited is a marker annotation that can be applied only on another annotation
declaration.
‰  It affects only annotations that will be applied on class declarations.
‰  @Inherited causes the annotation for a super class to be inherited by a subclass.
@Override
‰  @Override is a marker annotation that can be applied only on methods.
‰  A method annotated with @Override must override a method from a super class. If it
does not, then a compile-time error will result.
‰  It is used to ensure that a super class method is actually overridden, and not simply
overloaded.
@Deprecated
‰  @Deprecated is a marker annotation.
‰  It indicates that a declaration is obsolete and has been replaced by a new form.
@SuppressWarnings
‰  @SuppressWarnings specifies that one or more warnings that might be issued by the
compiler are to be suppressed.
‰  The warnings to suppress are specified by name, in string form.
‰  This annotation can be applied to any type of declaration.
Tips and Tricks:
Does the new feature in Java 2, v5.0 called ‘metadata’ is same as the ‘annotation’ feature?
Solution:
‰  Java 2, v5.0 adds a powerful new facility called metadata, which enables you to
embed supplemental information into a source file.
‰  This information, called an annotation, does not change the actions of a program.
‰  An annotation leaves the semantics of a program unchanged.
‰  However, this information can be applied by various tools, during both development
and deployment.
‰  For example, an annotation might be processed by a source-code generator.
‰  Although Sun refers to this feature as metadata, the term program annotation facility is
also applied, and is more descriptive.
Summary
‰  All annotation types automatically extend the Annotation interface.
‰  Thus Annotation is a super-interface of all annotations.
‰  The Annotation interface is declared within the java.lang.annotationpackage.
‰  It overrides hashCode(), equals(), and toString(), which are defined by Object.
‰  It also specifies annotationType(), which returns a Class object that represents the
invoking annotation.

Updates in JDK 1.6 - 51

Learning Objectives
After completing this session, you will be able to:
‰  Describe the key features of Java SE (Standard Edition) 6 (JDK 1.6)
The Java SE 6 (JDK 1.6) Top 10 Features
The top 10 features of JDK 1.6 are:
‰  Scripting
‰  Web Services
‰  Database (JDBC 4.0, Java DB)
‰  More Desktop APIs
‰  Monitoring and Management
‰  Compiler Access
‰  Pluggable Annotations
‰  Desktop Deployment
‰  Security
‰  Quality, Compatibility, and Stability
Motivation for Scripting Support
‰  Scripting support provides developers an opportunity to leverage the advantages of
different languages in the same application.
‰  It extends scripting languages applying the powerful Java technology libraries.
‰  It provides reuse of code modules in other programming languages.
‰  It produces an environment in which developers and end users can collaborate to
create more useful and dynamic applications.
‰  You can now mix in JavaScript technology with your Java technology source code,
useful for prototyping. Also useful when you have teams with a variety of skill sets.
oScripting for the Java Platform (JSR 223):
oMechanism for configuring script engines into Java SE
oAPIs for mixing script fragments into Java applications
oA JavaScript engine is included in the implementation of Java SE 6 of Sun:
oMozilla Rhino engine
oConformant scripting engines: scripting.java.net
Scripting: Developer Example
// create a ScriptEngineManager
ScriptEngineManager m = new ScriptEngineManager();
// get an instance of JavaScript script engine
ScriptEngine engine = m.getEngineByName("js");
// evaluate a script
engine.eval("alert(\"Hello World!\")");
Web Services Support on Java SE 6 Platform
‰  JAX-WS
‰  Data binding using JAXB 2.0
‰  Updates to the JAXP, which includes StaX
Standards supported are:
‰  SOAP 1.2
‰  WS-I Basic Profile 1.1
‰  XML-binary Optimized Packaging (XOP) and SOAP Message Transmission
Optimization Mechanism (MTOM)
‰  Representational State Transfer (REST)
‰  Totally on XML schema
API Support
‰  Java SE 6 provides support for the JAX- WS Web services stack.
‰  For the client side: Service class for creating proxy
‰  For the server side: Endpoint class for publication
Database: JDBC 4.0 Support
‰  Developers will get the updated JDBC 4.0, which focuses on ease of use.
‰  It contains many feature additions like support for XML as an SQL datatype and better
integration of Binary Large OBjects (BLOBs) and Character Large OBjects (CLOBs)
into the APIs.
‰  Additional features that improve ease of use include removal of some JDBC
boilerplate and some of the new annotations that make SQL strings embed better into
your JDBC application – like decorating your getAllUsers() method with an
@Query(sql=”select * from user”) annotation, and that being all you need.
Java DB
‰  Java DB is based on Apache Derby:
‰  JDBC conformant all-Java relational database
‰  Bundled and pre-configured in JDK
Desktop APIs
AWT (Abstract Window Toolkit) improvements are:
‰  Tray icon
‰  Splash screen
‰  Desktop class
‰  Dialog Modality enhancements and API
‰  Text printing
Swing improvement:
‰  GroupLayout: Basis for NetBeans GUI Builder (Matisse)
‰  JTable sorting and filtering
‰  SwingWorker
Splash Screen: Overview
‰  Before Java SE 6, Java run time needs to be fully loaded and initialized before a visual
image can be displayed.
‰  Splash screen allows displaying a splash screen for the application instantly before the
Java runtime software starts:
‰  GIF (Graphic Interchange Format), PNG (Portable Network Graphics), and JPEG
(Joint Photographic Experts Group) images supported
‰  Transparency, translucency, and animation supported
‰  Closed automatically when first top-level window displays
Splash Screen: Usage
Display from command line:
java -splash:image.gif TheApp
Display from MANIFEST.MF (in a jar file):
Splashscreen-Image: image.gif
Painting: You can change the image shown after the splash screen is loaded, but before the
application starts.
SplashScreen splash = SplashScreen.getSplashScreen();
Graphics2D g = splash.createGraphics();
// your painting code here
splash.update();
Desktop APIs
‰  GUI developers get a large number of new tricks to play like the ever popular yet
newly incorporated SwingWorker utility to help you with threading in GUI apps, JTable
sorting and filtering, and a new facility for quick splash screens to quiet impatient
users.
‰  Desktop class has an enumeration of actions that may be supported for a file or URI
like BROWSE, EDIT, MAIL, OPEN, and PRINT.
‰  File processing: Opening, editing, and printing files with applications registered in
native system
‰  Browsing: Opening a URL with the default browser
‰  Email: Sending a message with the default mail client
Dialog Modality Enhancement
‰  New modality model is introduced:
‰  This new model allows the developer to scope, or limit the modality blocking of a
dialog box, based on the modality type that the developer chooses.
‰  This new model allows windows and dialog boxes to be truly parentless.
‰  This new model solves the problem of interacting with JavaHelp in J2SE 1.5 when
modal dialog box is on the front.
Security
Security added important new APIs:
‰  XML Digital Signature (XMLDSig) API (JSR 105)
‰  Smart Card I/O API (JSR 268)
Security improved authentication schemes:
‰  JAAS-based authentication using LDAP
‰  Native Platform Java GSSAPI (Generic Security Services Application Programming
Interface)
Java SE 6 has simplified the job of its security administrators by providing various new ways to
access platform-native security services, such as native Public Key Infrastructure (PKI) and
cryptographic services on Microsoft Windows for secure authentication and communication, Java
Generic Security Services (Java GSS) and Kerberos services for authentication, and access to
LDAP servers for authenticating users.
Summary
‰  The key features of Java SE 6 (Mustang) (JDK 1.6) are:
oScripting
oWeb Services
oDatabase (JDBC 4.0, Java DB)
oMore Desktop APIs
oMonitoring and Management
oCompiler Access
oPluggable Annotations
oDesktop Deployment
oSecurity
oQuality, Compatibility, and Stability
Test Your Understanding
1.State true or false for the following:
a)JDBC 4.0 is available with Java SE v5 (Tiger).
b)With Java SE 6, applications can use JAX-WS to build web applications and web
services, incorporating the newer XML-based web services functionality.
c)A JavaScript engine named as Mozilla Rhino engine is included in the Sun’s
implementation of Java SE 6.

Saturday 3 August 2013

47:PreparedStatement and CallableStatement

Learning Objectives
After completing this session, you will be able to:
‰  Identify java.sql.PreparedStatement and java.sql.CallableStatement
Prepared and Callable Statements
‰  PreparedStatement:SQL is sent to the database and compiled or prepared
beforehand
‰  CallableStatement:Executes SQL Stored Procedures
PreparedStatement
‰  The contained SQL is sent to the database and compiled or prepared beforehand.
‰  From this point on, the prepared SQL is sent and this step is bypassed. The more
dynamic statement requires thisstep on every execution.
‰  Depending on the DB engine, the SQL may be cached and reused even for a different
PreparedStatement and most of the work isdone by the DB engine rather than the
driver.
‰  Instances of PreparedStatement contain an SQL statement that has already been
compiled. This is what makes a statement "prepared.“
‰  The SQL statement contained in a PreparedStatement object may have one or more
IN parameters.
‰  An IN parameter is a parameter whose value is not specified when the SQL statement
is created.
‰  Instead, the statement has a question mark (?) as a placeholder for each IN
parameter.
‰  The ? is also known as a parameter marker or parameter placeholder.
‰  An application must set a value for each parameter marker in a prepared statement
before executing the prepared statement.
‰  Because PreparedStatement objects are precompiled, their execution can be faster
than that of Statement objects.
‰  Consequently, an SQL statement that is executed many times is often created as a
PreparedStatement object to increase efficiency.
‰  Being a subclass of Statement, PreparedStatement inherits all the functionality of
Statement.
‰  In addition, it adds a set of methods that are needed for setting the values to be sent
to the database in place of the placeholders for IN parameters.
‰  Also, the three methods execute, executeQuery, and executeUpdate are modified so
that they take no argument.
‰  The Statement forms of these methods (the forms that take an SQL statement
parameter) cannot be used with a PreparedStatement object.
PreparedStatement Steps
The steps of PreparedStatement object are:
1.You register the drive and create the db connection in the usual manner.
2.Once you have a db connection, create the prepared statement object.
Example:
PreparedStatement updateSales =
con.prepareStatement(“UPDATE OFFER_TBL SET
QUANTITY = ? WHERE ORDER_NUM = ? ");
// “?” are referred to as Parameter Markers
// Parameter Markers are referred to by number,
// starting from 1, in left to right order.
// PreparedStatement's setXXX() methods are used to set
// the IN parameters, which remain set until changed.
Bind in your variables. The binding in of variables is based on position.
updateSales.setInt(1, 75);
updateSales.setInt(2, 10398001);
Once all the variables have been bound, then you execute the PreparedStatement.
int iUpdatedRecords = updateSales.executeUpdate();
If AutoCommit is set to true, then once the statement is executed, the changes are committed.
From this point forth, you can just re-use the PreparedStatement object.
updateSales.setInt(1, 150);
updateSales.setInt(2,10398002);
If the PreparedStatement object is a select statement, then you execute it, and loop through the
ResultSet object in the same way as in the basic JDBC example:
PreparedStatement itemsSold =
con.prepareStatement("select o.order_num,
o.customer_num, c.name, o.quantity from order_tbl o,
customer_tbl c where o.customer_num =
c.customer_num and o.customer_num = ?;");
itemsSold.setInt(1,10398001);
ResultSet rsItemsSold = itemsSold.executeQuery();
while (rsItemsSold.next()){
System.out.println( rsItemsSold.getString(“NAME") +
"sold "+ rsItemsSold.getString(“QUANTITY") + " unit(s)");
}
CallableStatement
‰  CallableStatement is the interface used to execute SQL stored procedures.
‰  A stored procedure is a group of SQL statements that form a logical unit and perform a
particular task.
‰  Stored procedures are used to encapsulate a set of operations or queries to execute
on a database server.
‰  A CallableStatement object contains a call to a stored procedure. It does not contain
the stored procedure itself.
‰  The following first line of code creates a call to the stored procedure
SHOW_SUPPLIERS using the connection con .
‰  The part that is enclosed in curly braces is the escape syntax for stored procedures.
CallableStatement cs = con.prepareCall("{call
SHOW_SUPPLIERS}");
ResultSet rs = cs.executeQuery();
CallableStatement Example
Here is an example using IN, OUT, and INOUT parameters.
// set int IN parameter
cstmt.setInt( 1, 333 );
// register int OUT parameter
cstmt.registerOutParameter( 2, Types.INTEGER );
// set int INOUT parameter
cstmt.setInt( 3, 666 );
// register int INOUT parameter
cstmt.registerOutParameter( 3, Types.INTEGER );
//You then execute the statement with no return value
cstmt.execute(); // could use executeUpdate()
// get int OUT and INOUT
int iOUT = cstmt.getInt( 2 );
int iINOUT = cstmt.getInt( 3 );
Stored Procedure Example
FUNCTION event_list ( appl_id_in VARCHAR2,
dow_in VARCHAR2,
event_type_in VARCHAR2 OUT,
status_in VARCHAR2 INOUT)
RETURN ref_cur;
Summary
‰  The SQL statement contained in a PreparedStatement object may have one or more
IN parameters.
‰  An application must set a value for each parameter marker in a prepared statement
before executing the prepared statement.
‰  Because PreparedStatement objects are precompiled, their execution can be faster
than that of Statement objects.
‰  Consequently, an SQL statement that is executed many times is often created as a
PreparedStatement object to increase efficiency.
‰  A CallableStatement object provides a way to call stored procedures in a standard
way for all RDBMSs.
‰  A stored procedure is stored in a database; the call to the stored procedure is what a
CallableStatement object contains.
‰  This call is written in an escape syntax that may take one of two forms: one form with
a result parameter and the otherwithout a result parameter.
‰  A result parameter, a kind of OUT parameter, is the return value for the stored
procedure.
Test Your Understanding
1.Differentiate between PreparedStatement and CallableStatement.
2.What is a significance of writing a stored procedure?

46:Connection Pooling

Learning Objectives
After completing this session, you will be able to:
‰  Define DataSource and Connection Pooling
‰  Describe transaction
javax.sql.DataSource Interface and DataSource Object
‰  Driver vendor implements the javax.sql.DataSource interface.
‰  DataSource object is the factory for creating database connections.
Three types of possible implementations are:
‰  Basic implementation: Produces standard Connection object
‰  Connection pooling implementation: Produces a Connection object that will
automatically participate in connection pooling
‰  Distributed transaction implementation: Produces a Connection object that may be
used for distributed transactions and almostalways participates in connection pooling
Properties of DataSource Object
A DataSource object has properties that can be modified when necessary. These are defined in
the configuration file of a container:
‰  Location of the database server
‰  Name of the database
‰  Network protocol to be used to communicate with the server
The benefit is that, because the properties of the data source can be changed, any code accessing
that data source does not need to be changed.
In the Sun Java System Application Server, a data source is called a JDBC resource.
Where are Properties of a DataSource Defined?
The properties of a DataSource are defined:
‰  In the configuration file of the container
‰  In Sun Java System App Server, they are defined in:
<J2EE_HOME>/domains/domain1/config/domain.xml
‰  In Tomcat, they are defined in server.xml:
<TOMCAT_HOME>/conf/server.xml
DataSource (JDBC Resource) Definition in domain.xml of Sun Java System
AppServer
<resources>
<jdbc-resource enabled="true" jndi-name="jdbc/BookDB" object-type=“
user” pool-name="PointBasePool"/>
<jdbc-connection-pool connection-validation-method=“auto-commit”
datasource-classname="com.pointbase.xa.xaDataSource" failallconnections="
false" idle-timeout-in-seconds="300" is-connectionvalidationrequired="false" is-isolation-level-guaranteed="true" maxpool-size="32"
max-wait-time-in-millis="60000" name="PointBasePool"
pool-resize-quantity="2" res-type="javax.sql.XADataSource"
steadypool-size="8">
<property name="DatabaseName"
value="jdbc:pointbase:server://localhost:9092/sun-appservsamples"/>
<property name="Password" value="pbPublic"/>
<property name="User" value="pbPublic"/>
</jdbc-connection-pool>
</resources>
JNDI Registration of a DataSource Object
‰  A driver that is accessed by a DataSource object does not register itself with the
DriverManager.
‰  Rather, a DataSource object is registered to JNDI naming service by the container and
then retrieved by a client though a lookup operation.
‰  With a basic implementation, the connection obtained through a DataSource object is
identical to a connection obtained through the DriverManager facility.
JNDI Registration of a DataSource (JDBC Resource) Object
The JNDI name of a JDBC resource is expected in the java:comp/env/jdbc subcontext. For
example, the JNDI name for the resource of a BookDB database could be
java:comp/env/jdbc/BookDB.
Because all resource JNDI names are in the java:comp/env subcontext, when you specify the
JNDI name of a JDBC resource, then enter only jdbc/name. For example, for a payroll database,
specify jdbc/BookDB.
Need of Connection Pooling
‰  Database connection is an expensive and limited resource. Using connection pooling,
a smaller number of connections are shared by a larger number of clients.
‰  Creating and destroying database connections are expensive operations.
‰  Using connection pooling, a set of database connections are created at firsthand and
made available in the pool.
‰  Then these connections are provided on requirement basis from the pool and finally
these connections are returned back to the pool.
‰  The important advantage of connection pooling mechanism is that it cuts down the
overhead of creating and destroying database connections.
Connection Pooling and DataSource
‰  DataSource objects that implement connection pooling also produce a connection to
the particular data source that the DataSource class represents.
‰  The Connection object that the getConnection method returns is a handle to a
PooledConnection object rather than being a physical connection. The application
code works in the same way.
Example: PointBasePool
‰  The Sun Java Application Server 8 is distributed with a connection pool named
PointBasePool, which handles connections to the PointBase database server.
‰  Under Sun Java Application Server, each DataSource object is associated with a
connection pool.
Retrieval and Usage of a DataSource Object
‰  Application perform JNDI lookup operation to retrieve DataSource object.
‰  DataSource object is then usedto retrieve a Connection object.
‰  In the web.xml file of the application, information on external resource, DataSource
object in this case, is provided.
‰  For Sun Java System App server, the mapping of external resource and JNDI name is
provided. This providesfurther flexibility.
Example: Retrieval of DataSource Object by JNDI
BookDBAO.java in bookstore1 application:
public class BookDBAO {
private ArrayList books;
Connection con;
private boolean conFree = true;
public BookDBAO() throws Exception {
try {
Context initCtx = new InitialContext();
Context envCtx = (Context)initCtx.lookup("java:comp/env");
DataSource ds = (DataSource)
envCtx.lookup("jdbc/BookDB");
con = ds.getConnection();
} catch (Exception ex) {
throw new Exception("Couldn't open connection to database: "
ex.getMessage());
}
}
}
JNDI Resource Information in web.xml of bookstore1
<resource-ref>
<res-ref-name>jdbc/BookDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
JNDI and Resource Mapping in sun-web.xml of bookstore1
<sun-web-app>
<context-root>/bookstore1</context-root>
<resource-ref>
<res-ref-name>jdbc/BookDB</res-ref-name>
<jndi-name>jdbc/BookDB</jndi-name>
</resource-ref>
</sun-web-app>
Transaction
‰  One of the main benefits of using a PreparedStatement is executing the statements in
a transactional manner.
‰  The committing of each statement when it is first executed is very time consuming.
‰  By setting AutoCommit to false, the developer can update the database more then
once and then commit the entire transaction as a whole.
‰  Also, if each statement is dependant on the other, the entire transaction can be rolled
back and the user is notified.
JDBC Transaction Methods
The JDBC transaction methods are:
‰  setAutoCommit():If set true, every executed statement is committed immediately
‰  commit():
oRelevant only if setAutoCommit(false)
oCommit operations performed because the opening of a Connection or last
commit() or rollback() calls
‰  rollback():
oRelevant only if setAutoCommit(false)
oCancels all operations performed
Transactions Example
Connection connection = null;
try {
connection =
DriverManager.getConnection("jdbc:oracle:thin:@machinename:1521:db
name","username","password");
connection.setAutoCommit(false);
PreparedStatement updateQty =
connection.prepareStatement("UPDATE STORE_SALES SET QTY = ? WHERE
ITEM_CODE = ? ");
int [][] arrValueToUpdate =
{ {123, 500} ,
{124, 250},
{125, 10},
{126, 350} };
int iRecordsUpdate = 0;
for ( int items=0 ; items < arrValueToUpdate.length ;
items++) {
int itemCode = arrValueToUpdate[items][0];
int qty = arrValueToUpdate[items][1];
updateQty.setInt(1,qty);
updateQty.setInt(2,itemCode);
iRecordsUpdate += updateQty.executeUpdate();
}
connection.commit();
System.out.println(iRecordsUpdate + " record(s) have been updated");
} catch(SQLException sqle) {
System.out.println("" + sqle);
}
try {
connection.rollback();
} catch(SQLException sqleRollback) {
System.out.println("" + sqleRollback);
} finally {
try {
connection.close();
}
catch(SQLException sqleClose) {
System.out.println("" + sqleClose);
}
}
Tips and Tricks:
Provide some key points on the transaction isolation level namely
TRANSACTION_READ_COMMITTED.
Solution:
‰  The programmer sets a property namely, the transaction isolation level, which
determines the transaction isolation level given to the connection that the rowset
establishes.
‰  The owner does not want to read any data that has not been committed, so the
programmer chooses the level TRANSACTION_READ_COMMITTED.
crset.setTransactionIsolation(Connection.TRANSACTION_READ_COMMI
TTED);
‰  When you set the transaction isolation level to TRANSACTION_READ_COMMITTED, it
will not allow a value to be accessed until after it has been committed, and forbids dirty
read.
‰  Now suppose that A and B both have a transaction isolation level of
TRANSACTION_READ_COMMITTED.
‰  This level prohibits reading a value that has changed until after it has been committed,
so neither A nor B will be able to make a "dirty read."
‰  In this situation, a sensitive result set open in transaction A will not show uncommitted
changes that B makes, but it will reflect a value updated by B after B commits the
change.
‰  A sensitive result set open in B will likewise show changes that A makes after A
commits them.
‰  Similar to this level, the other field values for isolation levels provided in the
Connection interface are TRANSACTION_READ_COMMITTED,
TRANSACTION_SERIALIZABLE, TRANSACTION_NONEand
TRANSACTION_REPEATABLE_READ.
‰  By default, the isolation level is set to TRANSACTION_SERIALIZABLE.
Summary
‰  DataSource
oThe DataSource interface provides methods that allow a user to get and set the
character stream to which tracing and error logging will be written.
oA user can trace a specific data source on a given stream, or multiple data
sources can write log messages to the samestream provided that the stream is
set for each data source.
‰  Connection Pooling
oGet the connection with a DataSource object
oAlways close the connection in a finally block.
‰  Distributed Transactions:
oDo not call the methods commit or rollback, and
oDo not set auto-commit mode to true.
Test Your Understanding
1.State true or false for the following:
a)The usage of Connection Pooling mechanism results in cutting down on the
overhead of creating and destroying database connections.
b)By setting AutoCommit to false, the developer cannotupdate the database more
than once and then commit the entire transaction as a whole.