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.

45:JDBC

Learning Objectives
After completing this session, you will be able to:
‰  Define JDBC
‰  Apply JDBC API step by step
JDBC
JDBC is a standard Java API for accessing relational database and hides database specific details
from application.
JDBC is a part of Java SE (J2SE). Java SE 6 has JDBC 4.
JDBC API
‰  The JDBC API is a Java API for accessing virtually any kind of tabular data.
‰  The JDBC API consists of a set of classes and interfaces written in the Java
programming language that provide a standard API for tool/database developers and
makes it possible to write industrial-strengthdatabase applications entirely in the Java
programming language.
‰  The Java programming language, being robust, secure, easy to use, easy to
understand, and automatically downloadable on a network, is an excellent language
basis for database applications.
‰  What is needed is a way for Java applications to talk to a variety of different data
sources. The JDBC API provides the mechanism for doing this.
‰  Majority of JDBC API is located in java.sql package, which are DriverManager,
Connection, ResultSet, DatabaseMetaData, ResultSetMetaData, PreparedStatement,
CallableStatement and Types
‰  The javax.sql package provides many advanced functionalities.
o  Example:DataSource
‰  For example, an alternative tothe DriverManager facility, a DataSource object is the
preferred means of getting a connection.
‰  The DataSource interface is implemented by a driver vendor.
‰  With a basic implementation, the connection obtained through a DataSource object is
identical to a connection obtained through the DriverManager facility.
JDBC Driver
JDBC driver is an implementation of JDBC interfaces that is specific to database. Every database
server has corresponding JDBC drivers.
You can see the list of available drivers from http://industry.java.sun.com/products/jdbc/drivers
JDBC Driver
In simplest terms, a JDBC technology-based driver ("JDBC driver") makes it possible to do three
things:
‰  Establish a connection with a data source
‰  Send queries and update statements to the data source
‰  Process the results
The following code fragment gives a simple example of these three steps:
Connection con = DriverManager.getConnection( "jdbc:myDriver:wombat",
"myLogin", "myPassword");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1");
while (rs.next()) {
int x = rs.getInt("a");
String s = rs.getString("b");
float f = rs.getFloat("c");
}
Database URL
Database URL is used to make a connection to the database and can contain server, port,
protocol, and so on.
jdbc:subprotocol_name:driver_dependant_databasename: Oracle thin driver
jdbc:oracle:thin:@machinename:1521:dbname:Derby
jdbc:derby://localhost:1527/sample: Pointbase
jdbc:pointbase:server://localhost/sample
Steps of Applying JDBC
The steps of applying JDBC are:
1.Load the JDBC driver that is specific to DB
2.Get a Connection object
3.Get a Statement object
4.Execute queries and/or updates
5.Read results
6.Read Meta-data (optional step)
7.Close Statement and Connection objects
Load DB-Specific Database Driver
Loading the driver or drivers you want to use is very simple and involves just one line of code.
If, for example, you want to use the JDBC–ODBC Bridge driver, the following code will load it:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Your driver documentation will give you the class name to use.
For instance, if the class name is jdbc.DriverXYZ, you would load the driver with the following line
of code:
Class.forName("jdbc.DriverXYZ");
You do not need to create an instance of a driver and register it with the DriverManager because
calling the method Class.forName will do that for you automatically.
If you were to create your own instance, you would be creating an unnecessary duplicate.
When you have loaded a driver, it is available for making a connection with a DBMS.
Get a Connection Object
DriverManager class is responsible for selecting the database and creating the database
connection.
Using DataSource is a preferred means of getting a Connection object (You will talk about
DataSource in the next session)
Create the database connection:
try {
Connection connection =
DriverManager.getConnection("jdbc:derby://localhost:1527/sample",
“app"," app ");
} catch(SQLException sqle) {
System.out.println("" + sqle);
}
DriverManager and Connection
java.sql.DriverManager: getConnection(String url, String user, String password) throws
SQLException
java.sql.Connection:
Statement createStatement() throws SQLException
void close() throws SQLException
void setAutoCommit(boolean b) throws SQLException
void commit() throws SQLException
void rollback() throws SQLException
Get a Statement Object
Create a Statement object from Connection object:
java.sql.Statement:
ResultSet executeQuery(string sql)
int executeUpdate(String sql)
Example: Statement statement = connection.createStatement();
The same Statement object can be used for many unrelated queries
Executing Query or Update
From the Statement object, the two most used commands are:
QUERY (SELECT) :
ResultSet rs = statement.executeQuery("select * from customer_tbl");
ACTION COMMAND (UPDATE/DELETE) :
int iReturnValue = statement.executeUpdate("update manufacture_tbl set
name = ‘IBM' where mfr_num = 19985678");
Reading Results
Loop through ResultSet retrieving information:
java.sql.ResultSet:
boolean next()
xxx getXxx(int columnNumber)
xxx getXxx(String columnName)
void close()
The iterator is initialized to a position before the first row. You must call next() once to move it to
the first row.
Once you have the ResultSet, you can easily retrieve the data by looping through it
while (rs.next()){
// Wrong this will generate an error
String value0 = rs.getString(0);
// Correct!
String value1 = rs.getString(1);
int value2 = rs.getInt(2);
int value3 = rs.getInt(“ADDR_LN1");
}
When retrieving data from the ResultSet, use the appropriate getXXX() method:
‰  getString()
‰  getInt()
‰  getDouble()
‰  getObject()
There is an appropriate getXXX() method of each java.sql.Types data type.
Read ResultSet MetaData and DatabaseMetaData (Optional)
Once you have the ResultSet or Connection objects, you can obtain the metadata about the
database or the query.
This gives valuable information about the data that you are retrieving or the database that you are
using.
ResultSetMetaData rsMeta = rs.getMetaData();
DatabaseMetaData dbmetadata = connection.getMetaData();
There are approximately 150 methods in the DatabaseMetaData class.
ResultSetMetaData Example
ResultSetMetaData meta = rs.getMetaData();
//Return the column count
int iColumnCount = meta.getColumnCount();
for (int i =1 ; i <= iColumnCount ; i++){
System.out.println(“Column Name: " + meta.getColumnName(i));
System.out.println(“Column Type" + meta.getColumnType(i));
System.out.println("Display Size: " +
meta.getColumnDisplaySize(i) );
System.out.println("Precision: " + meta.getPrecision(i));
System.out.println(“Scale: " + meta.getScale(i) );
}
Tips and Tricks:
Provide some key tips while writing SQL statements and executing it using executeUpdate()
methods.
Solution:
‰  When a connection is created using JDBC, bydefault it is in the auto-commit mode.
‰  This means that each individual SQL statementis treated as a transaction by itself,
and will be committed as soon as its execution is finished.
‰  Notice that for the SQL statements CREATE, INSERT, UPDATE, and DELETE, the
execution of the method executeUpdate() will change the state of the database.
‰  Whenever the SQL statement will not fit on one line on the page, you have to split it
into two strings concatenated by a plus sign (+) so that it will compile.
‰  Pay special attention to the space following “INSERT INTO tablename” to separate it
in the resulting string from “VALUES”.
Summary
Advantages of Java and JDBC technologies:
‰  MIS managers like the combination of the Java platform and JDBC technology
because it makes disseminating information easy and economical.
‰  Businesses can continue to use their installed databases and access information
easily even if it is stored on different database management systems or other data
sources.

Test Your Understanding
1.State true or false for the following:
a)Majority of JDBC API is located in java.sql package.
b)DriverManager class is notresponsible for selecting the database and creating the
database connection.
c)In the ResultSet class, there is an appropriate getXXX() method for each
java.sql.Types data type

44:Serialization

Learning Objectives
After completing this session, you will be able to:
‰  Define Serialization
‰  Identify what is preserved when an object is serialized
‰  Write Transient keyword
‰  Describe the process of serialization
‰  Explain the process of deserialization
‰  Define Version control
‰  Change the default protocol
‰  Create your own protocol by Externalizable interface
Serialization
Serialization is an ability to read or write an object to a stream. It is the process of "flattening" an
object.
Serialization is used to save object to some permanent storage. Its state should be written in a
serialized form to a file such that the object can be reconstructed at a later time from that file.
Serialization is used to pass on to another object bythe OutputStream class and can be sent over
the network.
Streams Used for Serialization
The streams used for serialization are:
‰  ObjectOutputStream:For serializing (flattening an object)
‰  ObjectInputStream:For deserializing (reconstructing an object)
Requirement for Serialization
‰  Serialization is required to allow an object to be serializable:
‰  Its class should implement the Serializable interface:
oSerializable interface is marker interface
oIts class should also provide a default constructor (a constructor with no
arguments)
‰  Serializability is inherited:
oDo not have to implement Serializable on every class
oCan just implement Serializable once along the class hierarchy
Non-Serializable Objects
‰  Most Java classes are serializable.
‰  Objects of some system-level classes are not serializable:
‰  Because the data that they represent, changes constantly:
‰  Reconstructed object will contain different value anyway
‰  For example, thread running in your JVM would be applying the memory of your
system. Persisting it and trying to run it inyour JVM would make no sense at all.
‰  A NotSerializableException is thrown if you try to serialize non-serializable objects
What is Preserved when an Object is Serialized?
When an object is serialized enough information ispreserved that is needed to reconstruct the
object instance at a later time:
‰  Only the data of the object is preserved
‰  Methods and constructors are not part of the serialized stream
‰  Class information is included
The transient Keyword
‰  The transient modifier applies only to instance variables.
‰  If you mark an instance variable as transient, you’re telling the JVM to skip (ignore)
this variable when you attempt to serialize the object containing it.
‰  In other words, the transient keyword prevents the data from being serialized.
‰  All fields that are not transient are considered part of the persistent state of an object
and are eligible for persistence.
Example: transient Keyword
1 class MyClass implements Serializable {
2
3 // Skip serialization of the transient field
4 transient Thread thread;
5 transient String fieldIdontwantSerialization;
6
7 // Serialize the rest of the fields
8 int data;
9 String x;
10
11 // More code
12 }
Serialization: Writing an Object Stream
To write an object stream use its writeObject method of the ObjectOutputStream class.
public final void writeObject(Object obj) throws IOException
where obj is the object to be written to the stream
1 import java.io.*;
2 public class SerializeBoolean {
3 SerializeBoolean() {
4 Boolean booleanData = new Boolean("true");
5 try {
6 FileOutputStream fos = new
7 FileOutputStream("boolean.ser");
8 ObjectOutputStream oos = new
9 ObjectOutputStream(fos);
10 oos.writeObject(booleanData);
11 oos.close();
12
13 } catch (IOException ie) {
14 ie.printStackTrace();
15 }
16 }
17
18 public static void main(String args[]) {
19 SerializeBoolean sb = new SerializeBoolean();
20 }
21 }
Deserialization: Reading an Object Stream
To read an object stream use its readObjectmethod of the ObjectInputStream class.
public final Object readObject()
throws IOException, ClassNotFoundException
where obj is the object to be read from the stream
The Object type returned should be typecasted to the appropriate class name before methods on
that class can be executed.
1 import java.io.*;
2 public class UnserializeBoolean {
3 UnserializeBoolean() {
4 Boolean booleanData = null;
5 try {
6 FileInputStream fis = new
7 FileInputStream("boolean.ser");
8 ObjectInputStream ois = new
9 ObjectInputStream(fis);
10 booleanData = (Boolean) ois.readObject();
11 ois.close();
12
13 } catch (Exception e) {
14 e.printStackTrace();
15 }
16 System.out.println("Unserialized Boolean from "
17 + "boolean.ser");
18 System.out.println("Boolean data: " +
19 booleanData);
20 System.out.println("Compare data with true: " +
21 booleanData.equals(new Boolean("true")));
22 }
23
24 public static void main(String args[]) {
25 UnserializeBoolean usb =
26 new UnserializeBoolean();
27 }
28 }
Version Control: Problem Scenario
‰  Imagine that you create a class, instantiateit, and write it out to an object stream.
‰  The flattened object sits in the file system for some time.
‰  Meanwhile, you update the class file, perhaps adding a new field.
‰  What happens when you try to read in the flattened object?
‰  An exception will be thrown specifically, the java.io.InvalidClassException.
Unique Identifier
Why exception is thrown?
‰  Because all classes that are capable ofpersistence have a unique identifier
automatically
‰  If the identifier of the class does not equal the identifier of the flattened object, then the
exception will be thrown
However, if you really think about it, why should it be thrown just because I added a field? Could
not the field just be set to its default value and then written out next time?
Yes, but it takes a little code manipulation. The identifier that is part of all classes is maintained in
a field called serialVersionUID.
If you wish to control versioning, then you simply have to provide the serialVersionUID field
manually and ensure that it is always the same, no matter what changes you make to the class
file.
How do you Generate a Unique ID?
serialver utility is used to generate a unique ID
Example:
serialver MyClass
MyClass static final long serialVersionUID = 10275539472837495L;
Provide your own implementation for readObject() and writeObject() methods
Classes that require special handling during the serialization and deserialization process must
implement special methods with these exact signatures:
‰  private void writeObject(java.io.ObjectOutputStream out)
throws IOException;
‰  private void readObject(java.io.ObjectInputStream in) throws
IOException, ClassNotFoundException;
Provide your own implementation for readObject() and writeObject() methods
The most common reason to implement writeObject() and readObject() is when you have to save
some part of an object’s state manually. If you choose, you can write and read ALL of the state
yourself, but that’s very rare.
When you want to do only a part of the serialization/deserialization yourself, you MUST invoke the
defaultReadObject() and defaultWriteObject() methods to do the rest.
Externalizable Interface
The writeExternal and readExternal methods ofthe Externalizable interface can be implemented
by a class to give the class complete control over the format and contents of the stream for an
object and its super types.
These methods must explicitly coordinate with the super type to save its state.
These methods supersede customized implementations of writeObject() and readObject()
methods.
How does Object Serialization Scheme works with Externalizable
Object Serialization applies the Serializable and Externalizable interfaces
Each object to be stored is tested for the Externalizable interface:
‰  If the object supports Externalizable, thenthe writeExternal() method is called.
‰  If the object does not support Externalizable and does implement Serializable, then
the object is saved using ObjectOutputStream.
Tips and Tricks:
1.Why will you ever write a class that was notserializable?
2.What happens if two objects in the object graph are the same object? Does this object get
saved twice during serialization?
Solution:
1.There are very few reasons, but you might for example, have a security issue where you
do not have a password object stored or you might have an object that makes no sense to
save, because its key instance variables are themselves not serializable, so there is no
useful way for you to make your class serializable.
2.Serialization is smart enough to know when two objects in the graph are the same. In that
case, only one of the objects is saved, and during deserialization, any references to that
single object are restored.
Summary
‰  A class must implement the Serializable interface before its objects can be serialized.
‰  If you mark an instance variable transient, it will not be serialized even though the rest
of the object’s state will be.
‰  If a superclass implements Serializable, then its subclasses do automatically.
‰  If a superclass doesn’t implement Serializable, then when a subclass object is
deserialized, the superclass constructor will run.
Test Your Understanding
1.What is object serialization?
2.What useful purpose does serializationserve?

43:Random Access Files

Learning Objectives
After completing this session, you will be able to:
‰  Apply Random Access Files
Random Access File
Random access files permit nonsequential, or random, access to the contents of a file.
Problem Scenario
Consider the archive format known as ZIP. A ZIP archive contains files and is typically
compressed to save space. It also contain a directory entry at the end that indicates where the
various files contained within the ZIP archive begin, as shown in the following figure:
Suppose that you want to extract a specific file from a ZIP archive. If you use a sequential access
stream, then you have to:
‰  Open the ZIP archive
‰  Search through the ZIP archive until you locate the file you want to extract
‰  Extract the file
‰  Close the ZIP archive
Using the procedure referred in the earlier slide,on average, you would have to read half the ZIP
archive before finding the file that you want to extract.
You can extract the same file fromthe ZIP archive more efficiently by using the seek feature of a
random access file and following these steps:
‰  Open the ZIP archive
‰  Seek to the directory entry and locate the entryfor the file you want to extract from the
ZIP archive
‰  Seek (backward) within the ZIP archive to the position of the file to extract
‰  Extract the file
‰  Close the ZIP archive
Benefits of Random Access File
Random Access File algorithm is more efficientbecause you read only the directory entry and the
file that you want to extract.
java.io.RandomAccessFile
‰  The java.io.RandomAccessFile class implements both the DataInput and DataOutput
interfaces.
‰  The java.io.RandomAccessFile class can be used for both reading and writing.
Creating a Random Access File
Similar to the sequential FileInputStream and FileOutputStream classes, you specify a file to be
opened by name when you instantiate an object of class RandomAccessFile. You can specify the
file name either by a literal string or by passing a File object which you have previously
instantiated.
Unlike with the sequential classes, when you instantiate an object of RandomAccessFile, you must
indicate whether you will just be reading the file, or also writing to it. You must be able to read a file
before you can write to it.
The syntax for instantiating a RandomAccessFile object is as follows:
new RandomAccessFile(name, mode)
As mentioned earlier, the name can be specified using either a literal string or an object of type
File.
The mode is a literal string which can be either of two possibilities:
‰  "r" means open for reading only
‰  "rw" means open for both reading and writing
Once the file is opened you can use the various forms of the read___() and write___() methods to
read and write the data in the file.
The following code creates a RandomAccessFile to read the file named xanadu.txt:
new RandomAccessFile("xanadu.txt", "r");
This one opens the same file for both reading and writing:
new RandomAccessFile("xanadu.txt", "rw");
After the file has been opened, you can use the common read or write methods defined in the
DataInput and DataOutput interfaces to perform I/O on the file.
File Pointer
‰  RandomAccessFile supports the notion of a file pointer.
‰  The file pointer indicates the current location in the file.
‰  When the file is first created, the file pointer is set to zero, indicating the beginning of
the file.
‰  Calls to the read and write methods adjust the file pointer by the number of bytes read
or written.
RandomAccessFile Methods
‰  RandomAccessFile contains the normal file I/O methods for implicitly manipulating the
file pointer.
‰  RandomAccessFile also contains the following three methods for explicitly
manipulating the file pointer:
o  int skipBytes(int):Moves the file pointer forward the specified number of
bytes
o  void seek(long):Positions the file pointer just before the specified byte
o  long getFilePointer():Returns the current byte location of the file pointer
Try It Out
Problem Statement:
Write a program that illustrates the usage of RandomAccessFile.
Code:
import java.io.*;
public class RandomIOApp {
public static void main(String args[]) throws IOException {
RandomAccessFile file = new RandomAccessFile("test.txt",
"rw");
file.writeBoolean(true);
file.writeInt(123456);
file.writeChar('j');
file.writeDouble(1234.56);
// Use seek() to move to a specific file location
file.seek(1);
System.out.println(file.readInt());
System.out.println(file.readChar());
System.out.println(file.readDouble());
file.seek(0);
System.out.println(file.readBoolean());
file.close();
}
}
How It Works:
‰  The RandomIOApp programprovides a simple demonstration of the capabilities of
random-access I/O.
‰  It writes a boolean, int, char, and double value to a file and then uses the seek()
method to seek to offset location 1 within the file. This is the position after the first byte
in the file.
‰  It then reads the int, char, and double values from the file and displays them to the
console window.
‰  Next, it moves the file pointer to the beginning of the file and reads the boolean value
that was first written to the file.
‰  This value is also written to the console window.
‰  The output of the program is as follows:
123456
j
1234.56
True
Tips and Tricks:
What is the difference between the File and RandomAccessFile classes?
Solution:The File class encapsulates the files and directories of the local file system. The
RandomAccessFile class provides the methods needed to directly access data contained in any
part of a file.
Summary
‰  Random access files permit nonsequential, or random, access to the contents of a file.
‰  The RandomAccessFile class implements both the DataInput and DataOutput
interfaces and therefore can be used for both reading and writing.
‰  RandomAccessFile supports the notion of a file pointer.
‰  RandomAccessFile contains the following three methods for explicitly manipulating the
file pointer.
o  skipBytes:Moves the file pointer forward the specified number of bytes.
o  seek:Positions the file pointer just before the specified byte.
o  getFilePointer:Returns the current byte location of the file pointer.
Test Your Understanding
1.State true or false for the following:
a)RandomAccessFile is the onlybidirectional stream in Java.
b)A random access file can be opened in ‘r’ mode or ‘rw’ mode.

42:I/O operations in JAVA

Learning Objectives
After completing this session, you will be able to:
‰  Define an I/O stream
‰  Identify the types of streams
‰  Explain the Stream class hierarchy
I/O Streams
‰  An I/O Stream represents an input source or an output destination.
‰  A stream can represent many different kinds of sources and destinations like disk files,
devices, other programs, a network socket, and memory arrays.
‰  Streams support many different kinds of data like simple bytes, primitive data types,
localized characters, and objects.
‰  Some streams simply pass on data, others manipulate and transform the data in
useful ways.
‰  No matter how they work internally, all streams present the same simple model to
programs that use them. A stream is a sequence of data.
Input Stream
A program uses an input stream to read data from a source, one item at a time.





 Output Stream
A program uses an output stream to write data to a destination, one item at time.


 General Stream Types
The general stream types are:
‰  Character and Byte Streams: Character streams are the streams that read and write
16-bit characters whereas Byte streams are the streams that read and write 8-bit
bytes.
‰  Input and Output Streams: Based on source or destination
‰  Node and Filter Streams: Whether the data on a stream is manipulated or transformed
or not.
Character and Byte Streams
‰  Byte streams:For binary data
‰  Root classes for byte streams:
oThe InputStream class
oThe OutputStream class
oBoth classes are abstract
‰  Character streams:For Unicode characters
‰  Root classes for character streams:
oThe Reader class
oThe Writer class
oBoth classes are abstract
Input and Output Streams
‰  Input or source streams: Can read from these streams
‰  Root classes of all input streams:
oThe InputStream class
oThe Reader class
‰  Output or sink (destination) streams: Can write to these streams
‰  Root classes of all output streams:
oThe OutputStream class
oThe Writer class
Node and Filter Streams
‰  Node streams (Data sink stream):Contain the basic functionality of reading or
writing from a specific location
‰  Types of node streams include files, memory, and pipes
‰  Filter streams (Processing stream):Layered onto node streams between threads or
processes
‰  For additional functionality like altering or managing data in the stream
‰  Adding layers to a node stream is called stream chaining
Streams
Streams are shown in the following diagram:
Tips and Tricks:
‰  How many bits are used torepresent Unicode, ASCII, UTF-16, and UTF-8 characters?
‰  What is the default character encoding of your platform?
Solution:
‰  Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set
uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using
8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.
‰  If you are running Java on English Windows platforms, then it is probably Cp1252. If
you are running Java on English Solaris platforms, then it is most likely 8859_1.
Summary
‰  The central building block of the Java I/O framework is the stream. “A stream is a
flowing sequence of characters”.
‰  In other words, a stream is usually considered to be an abstraction for the capability to
move bytes from a source to a sink.
‰  Input operations begin by openinga stream from the source and using a read()
method to obtain the data via the stream. Similarly, output operations begin by
opening a stream to the destination and using a write() method to send the data.
‰  The package named java.iocontains a set of input and output stream classes that can
be used to read and write data.
‰  The java.iopackage also provides specialized InputStream and OutputStream
subclasses that are used for specialized types of input and output.
‰  The InputStream class and OutputStream class are abstract superclasses that define
the behavior for sequential input and output streams in Java.
‰  Classes in java.iopackage are designed to be “chained” or “wrapped”. (This is a
common use of the decorator design pattern.)
Test Your Understanding
1.What is a ‘stream’?
2.Name some important input and output stream classes.
3.OutputStream and InputStreamclasses serve as the base classes for all byte stream
classes. Comment on this statement.

41:Concurrency Utilities

Learning Objectives
After completing this session, you will be able to:
‰  List the Concurrency Utilities
Concurrency Utilities: JSR-166
‰  Concurrency utilities enable development ofsimple yet powerful multi-threaded
applications. Like Collection it provides rich data structure handling capability.
‰  It beats C performance in high-end server applications.
‰  It provides richer set of concurrency building blocks. wait() , notify() , and synchronized
methods are too primitive.
‰  It enhances scalability, performance, readability, and thread safety of Java
applications.
Why Use Concurrency Utilities?
Concurrency utilities are used because:
‰  Reduced programming effort
‰  Increased performance
‰  Increased reliability: Eliminate threading hazards such as deadlock, starvation, race
conditions, or excessive context switching are eliminated
‰  Improved maintainability
‰  Increased productivity
Concurrency Utilities
The Concurrency Utilities are:
‰  Task Scheduling Framework
‰  Callable's and Future's
‰  Synchronizers
‰  Concurrent Collections
‰  Atomic Variables
‰  Locks
‰  Nanosecond-granularity timing
Task Scheduling Framework
‰  Executor /ExecutorService/Executors framework supports:
oStandardizing invocation
oScheduling
oExecution
oControl of asynchronous tasks according to a set of execution policies
‰  Executor is an interface
‰  ExecutorService extends Executor
‰  Executors is factory class for creating various kinds of ExercutorService
implementations
Executor Interface
‰  Executor interface provides a way of de-coupling task submission from the execution:
‰  Execution: Mechanics of how each task will be run, including details of thread use and
scheduling
‰  Example:
o  Executor executor = getSomeKindofExecutor();
o  executor.execute(new RunnableTask1());
o  executor.execute(new RunnableTask2());
‰  Many Executor implementations impose some sort of limitation on how and when
tasks are scheduled.
Executor and ExecutorService
ExecutorService adds lifecycle management:
public interface Executor {
void execute(Runnable command);
}
public interface ExecutorService extends Executor {
void shutdown();
List<Runnable> shutdownNow();
boolean isShutdown();
boolean isTerminated();
boolean awaitTermination(long timeout,
TimeUnit unit);
// other convenience methods for submitting tasks
}
Creating ExecutorService From Executors
public class Executors {
static ExecutorService
newSingleThreadedExecutor();
static ExecutorService
newFixedThreadPool(int n);
static ExecutorService
newCachedThreadPool(int n);
static ScheduledExecutorService
newScheduledThreadPool(int n);
// additional versions specifying ThreadFactory
// additional utility methods
}
Code example of poor resource management (pre-J2SE 5.0 code)
class WebServer {
public static void main(String[] args) {
ServerSocket socket = new ServerSocket(80);
while (true) {
final Socket connection =
socket.accept();
Runnable r = new Runnable() {
public void run() {
handleRequest(connection);
}
};
// Don't do this!
new Thread(r).start();
}
}
}
Code example for better resource management (Using Executors of Java2,v5.0)
class WebServer {
Executor pool =
Executors.newFixedThreadPool(7);
public static void main(String[] args) {
ServerSocket socket = new ServerSocket(80);
while (true) {
final Socket connection =
socket.accept();
Runnable r = new Runnable() {
public void run() {
handleRequest(connection);
}
};
pool.execute(r);
}
}
}
Callable's and Future's: Problem (pre-J2SE 5.0)
If a new thread (callable thread) is started in an application, then there is currently no way to return
a result from that thread to the thread (calling thread) that started it without the use of a shared
variable and appropriate synchronization. This is complex and makes code harder to explain and
maintain.
Callables and Futures
‰  Callable thread (Callee) implements Callable interface: Implement call() method rather
than run()
‰  Calling thread (Caller) submits Callable object to Executor and then moves on through
submit() and not execute()
‰  The submit() returns a Future object
‰  Calling thread (Caller) retrieves the result using get() method of Future object:
‰  If result is ready, then it is returned
‰  If result is not ready, then calling thread will block
Build CallableExample (This is Callee)
class CallableExample
implements Callable<String> {
public String call() {
String result = “The work is ended”;
/* Do some work and create a result */
return result;
}
}
Future Example (Caller)
ExecutorService es =
Executors.newSingleThreadExecutor();
Future<String> f =
es.submit(new CallableExample());
/* Do some work in parallel */
try {
String callableResult = f.get();
} catch (InterruptedException ie) {
/* Handle */
} catch (ExecutionException ee) {
/* Handle */
}
Semaphores
‰  Semaphores are typically used to restrict access to fixed size pool of resources.
‰  New Semaphore object is created with same count as number of resources.
‰  Thread trying to access resource, calls the aquire() method:
oReturns immediately if semaphore count is greater than zero
oBlocks if count is zero until release() is called by different thread
oaquire() and release() are thread safe atomic operations
Semaphore Example
private Semaphore available;
private Resource[] resources;
private boolean[] used;
public Resource(int poolSize) {
available = new Semaphore(poolSize);
/* Initialise resource pool */
}
public Resource getResource() {
try { available.aquire() } catch (IE) {}
/* Acquire resource */
}
public void returnResource(Resource r) {
/* Return resource to pool */
available.release();
}
BlockingQueue Interface
‰  BlockingQueue interface provides thread safeway for multiple threads to manipulate
collection.
‰  ArrayBlockingQueue is the simplest concrete implementation.
‰  Full set of methods are:
oput()
ooffer() [non-blocking]
opeek()
otake()
opoll() [non-blocking and fixed time blocking]
Blocking Queue Example 1
private BlockingQueue<String> msgQueue;
public Logger(BlockingQueue<String> mq) {
msgQueue = mq;
}
public void run() {
try {
while (true) {
String message = msgQueue.take();
/* Log message */
}
} catch (InterruptedException ie) {
/* Handle */
}
}
Blocking Queue Example 2
private ArrayBlockingQueue messageQueue =
new ArrayBlockingQueue<String>(10);
Logger logger = new Logger(messageQueue);
public void run() {
String someMessage;
try {
while (true) {
/* Do some processing */
/* Blocks if no space available */
messageQueue.put(someMessage);
}
} catch (InterruptedException ie) { }
}
Atomics
java.util.concurrent.atomic is a small toolkit of classes that support lock-free threadsafe
programming on single variables.
AtomicInteger balance = new AtomicInteger(0);
public int deposit(integer amount) {
return balance.addAndGet(amount);
}
Locks
Lock interface:
‰  More extensive locking operations than synchronized block
‰  No automatic unlocking, use try and finally to unlock
‰  Non-blocking access using tryLock()
ReentrantLock:
‰  Concrete implementation of Lock
‰  Holding thread can call lock() multiple times and not block
‰  Useful for recursive code
ReadWriteLock
ReadWriteLock has two locks controlling read and write access:
‰  Multiple threads can acquire the read lock if no threads have a write lock.
‰  If a thread has a read lock, then others can acquire read lock but nobody can acquire
write lock.
‰  If a thread has a write lock, then nobodycan have read or write lock.
‰  Methods to access locks are rwl.readLock().lock(); and rwl.writeLock().lock();
ReadWrite Lock Example
class ReadWriteMap {
final Map<String, Data> m = new TreeMap<String, Data>();
final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
final Lock r = rwl.readLock();
final Lock w = rwl.writeLock();
public Data get(String key) {
r.lock();
try { return m.get(key) }
finally { r.unlock(); }
}
public Data put(String key, Data value) {
w.lock();
try { return m.put(key, value); }
finally { w.unlock(); }
}
public void clear() {
w.lock();
try { m.clear(); }
finally { w.unlock(); }
}
}
Try It Out
Problem Statement:
Write a program that illustrates the usage of wait() and notify() methods in controlling access to a
shared resource.
Code:
class ThreadUsingWaitAndNotifyApp {
public static void main(String args[]) {
Resource resource = new Resource();
Thread controller = new Thread(new Controller(resource));
Thread[] user = new Thread[3];
for (int i = 0; i < user.length; ++i)
user[i] = new Thread(new User(i, resource));
controller.start();
for (int i = 0; i < user.length; ++i)
user[i].start();
boolean alive;
out: do {
alive = false;
Summary
‰  When a thread goes to sleep, its locks will be unavailable to other threads.
‰  All three methods namely wait(), notify(), and notifyAll() must be called from within a
synchronized context! A thread invokes wait()or notify() on a particular object, and the
thread must currently hold the lock on that object.
‰  Basically, a wait() call means “wait me in your pool,”, or “add me to your waiting list.”
‰  The notify() method is used to signal toone and only one of the threads that are
waiting in that same object’s waiting pool.
‰  The notify() method can NOT specify which waiting thread to notify.
Test Your Understanding
1.Name some of the concurrency utilities.
2.Why should you use concurrency utilities?