ERJEEML101 - JavaProgramming Part 2 PDF
ERJEEML101 - JavaProgramming Part 2 PDF
ER/CORP/CRS/ERJEEML101/003
Session Plan
• Multithreading
• Concurrency
• Input Output Streams & Serialization
• JDBC
• Java Beans
• Generics
• Annotations
2
Java Programming Part 2
Module 1 - Multithreading
ER/CORP/CRS/ERJEEML101/003
Lesson Outcomes
• After completion of the module you will be able to
understand about
– Creating and managing threads
– Priority management
– Thread synchronization
– Thread groups and daemon threads
Two ways:
• Extending the Thread class
• Implementing the Runnable interface
}}
class RunnableThreadMain
{
public static void main(String a[])
{
System.out.println("Hi I'm main thread");
RunnableThread rt=new RunnableThread();
Thread t=new Thread(rt);
t.start();
System.out.println("Hi I'm main thread");
}}
NEWBORN DEAD
start() run() returns or
thread interrupted
notify(), notifyAll()
WAITING RUNNABLE
Sleep interval
expires
yield() or end schedule
of time slice
SLEEPING sleep() wait()
NON-RUNNABLE
ALIVE
int bankBalance;
public synchronized void debitAccount (int amount) {
while((bankBalance - amount)<0) wait();
bankBalance -= amount;
…
}
public synchronized void creditAccount (int amount) {
bankBalance += amount;
notify();
…
}
}
ER/CORP/CRS/ERJEEML101/003
Concurrency
• Packages added in Java 5 for the support of concurrent programming are
– java.util.concurrent
• Contains classes and interfaces useful in concurrent programming
– java.util.concurrent.locks
• Contains interfaces and classes providing a framework for locking
and waiting for conditions that is distinct from built-in synchronization
and monitors.
– java.util.concurrent.atomic
• Contains classes that support lock-free thread-safe programming on
single variables.
• There are also new concurrent data structures added in the Java Collections Framework.
• Need for high level APIs
– Reduced Programmer effort
– Increased performance
– Improved maintainability
– Increased reliability
We enable you to leverage knowledge
27
anytime, anywhere!
Task Scheduling Framework
• As discussed in Module 1 there are two ways to create threads.
– Extending the Thread class
• Extend the Thread class
• Override the run() method
• Create an object of the sub class and call the start method to execute
the Thread
– Implementing the Runnable interface
• Useful when the class is already extending another class and needs to
implement mutithreading
• Implement the run() method
• Create a thread object (the worker) and give it a Runnable object (the
job)
• Start the thread by calling the start() method
• This works fine for smaller applications but in larger applications the thread
management and creation has to be separated from the rest of the application.
• This can be done by Executor which facilitates the standardized invocation,
scheduling and execution of threads..
We enable you to leverage knowledge
28
anytime, anywhere!
Task Scheduling Framework(Contd..)
• Executor Interface
– This interface provides a way of decoupling task submission from the
mechanics of how each task will be run, including details of thread use,
scheduling, etc.
– An Executor is normally used instead of explicitly creating threads.
– Example:
Executor executor = anExecutor;
executor.execute(new RunnableTask1());
– Many Executor implementations impose some sort of limitation on how and
when tasks are scheduled.
• ExecutorService Interface
– Extends Executor interface
– Has features that help manage the lifecycle of both the individual tasks and
the executor itself.
• Executors
– It is a factory for creating various kinds of ExecutorService
implementations.
We enable you to leverage knowledge
29
anytime, anywhere!
Task Scheduling Framework(Contd..)
import java.util.concurrent.*;
class RunnableThread implements Runnable
{
RunnableThread()
{
System.out.println("Child Thread: ");
}
public void run()
{
System.out.println("Hi I'm a new thread");
}
}
public class Main {
public static void main(String[] args) {
ExecutorService e1=Executors.newSingleThreadExecutor();
e1.execute(new RunnableThread()); } }
ER/CORP/CRS/ERJEEML101/003
Lesson Outcomes
• After completion of the module you will be able to
understand about
– What are Streams?
– What are the types of streams available?
– What are the classes available to work with streams?
– How the buffered streams are advantageous over the
non-buffered streams?
– What is Serialization?
Reads
Source Stream Program
Writes
InputStream
ByteArrayInputStream
FilterInputStream FileInputStream
BufferedInputstream ObjectInputStream
DataInputStream
PushbackInputStream
OutputStream ByteArrayOutputStream
FilterOutputStream FileOutputStream
BufferedOutputstream ObjectOutputStream
DataOutputStream
PrintStream
writeDouble(double)
writeBoolean(boolean)
writeXXX(XXX)
double readDouble()
boolean readBoolean()
XXX readXXX()
dos.writeInt(300);
dos.writeDouble(345.67);
dos.writeBoolean(true);
dos.close();
System.out.println(dis.readInt());
System.out.println(dis.readDouble());
System.out.println(dis.readBoolean());
dis.close();
ObjectOutputStream(OutputStream)
Module 4 - JDBC
ER/CORP/CRS/ERJEEML101/003
Lesson Outcomes
• After completion of the module you will be able to
understand
– What is JDBC?
– What are the advantages of using JDBC?
– How to work with a database using JDBC? and
– Transaction control in JDBC.
JDBC API
ODBC Driver
DataBase
JDBC API
DataBase
JDBC API
Network-Protocol driver
(Type III Driver)
MiddleWare
(Application Server)
JDBC API
DataBase
• DriverManager class :
– Manages all the JDBC Drivers that are loaded in
the memory
– Helps in dynamic loading of Drivers
• Data Source :
– Offer the user considerably more capability than
the basic Connection objects that the
DriverManager provides.
– It supports connection pooling and distributed
transactions
CallableStatement callableStatement =
connection.prepareCall("begin GetSalary(?,?); end;");
callableStatement.setInt(1,29418);
// OUT parameters must be registered.
callableStatement.registerOutParameter(2,Types.DOUBLE);
callableStatement.execute();
System.out.println("Salary : " + callableStatement.getDouble(2));
• Transactions
– The capability to group SQL statements for execution
as a single entity is provided through SQL’s
transaction mechanism.
– A transaction consists of one or more statements that
are executed, completed and either committed or
rolled back as a group.
– The commit means that the change is made
permanently in the database, and the term rollback
means that no change is made in the database.
try{
//Statements
connection.commit();
}
catch(Exception exception){
connection.rollback();
}
ER/CORP/CRS/ERJEEML101/003
Lesson Outcomes
• Reflection API
• Naming conventions
Module 6: Generics
ER/CORP/CRS/ERJEEML101/003
Why Generics?
• Many algorithms work in a similar way irrespective of the data
types on which they are applied on
– All Stacks work in a similar way irrespective of they type of
object they hold
• Generics help to write algorithms independent of a data type.
• Generic programming in earlier versions of Java uses “Object”
as the basic element of a data structure.
• For example Generic Stack has methods which works with
Objects Class Stack
{
..
public Object push(Object item) {..}
public Object pop(){..}
..}
• Example:
class Hashtable<K,V>{
..
public V put(K key, V value) { ..}
..
}
– Use of “<? extends Number>” sets sumOfElements method to accept Lists of type List<Number>
or a List of instances of a Number subclass, such as List<Integer>, List<Float>, List<Double> etc
and not others.
– Keyword: super.
– Example:
• sumOfElements(List<? super Integer> li){..}
– Use of “<? super Integer>” sets sumOfElements
method to accept List of type List< Integer> or a List
of instances of Integer superclass, such as
List<Number> and List<Object> and not others.
interface List<T>{
public void put(T element, int position);
public T get(int position);
}
ER/CORP/CRS/ERJEEML101/003
Agenda
• Overview
• Introduction to Annotations
• Annotation Basics
• Built-in Annotations
– @override
– @deprecated
– @SuppressWarnings
• Meta Annotations
• Accessing Annotation at Runtime
• Annotation Inheritance
• Advantages of Annotations
• References
We enable you to leverage knowledge
161
anytime, anywhere!
Overview
• Annotations, a new feature in J2SE 5.0 brings a much-
needed metadata facility to the core java language.
• If no values,
– No parentheses needed.
We enable you to leverage knowledge
164
anytime, anywhere!
Annotation Basics
• Annotatable Program elements:
– package
– class, including
• interface
• enum
– method
– field
– only at compile time
• local variable
• Formal parameter
Annotations
Marker Multi-valued
Single-valued
Annotations Annotations
Annotations
(With more
(with no member ) (With single
Than one
member)
Member)
Example:-
•@MarkerAnnotation()
•@SingleValueAnnotation("my data")
•@MultiValuedAnnotation(var1="data value 1",
•var2="data value 2", var3="data value 3").
javac User.java
@Override
public boolean equals(Object o) {
return true; } }
• Let's start with the following class. Notice that the class is
missing a break statement for each case of the switch
statement:
int i = args.length;
switch (i) {
case 0: System.out.println("0");
case 1: System.out.println("1");
case 2: System.out.println("2");
case 3: System.out.println("3");
default: System.out.println("Default");
}
} }
• @Documented
• @Inherited
• @Target
• @Retention
• @Documented
– javadoc should be generated when this annotation is
applied to an element
– Is the use of the annotation part of the public API
@Inherited
– Does the annotated get applied to subclasses or to
the base type?
– only works on classes
• not overriden methods
• not interfaces
We enable you to leverage knowledge
176
anytime, anywhere!
Meta-Annotations
• @Target
– Where the annotation can be used
• What kind of source elements
• Defaults in all
ElementType[] value();
@Retention(value=RetentionPolicy.RUNTIME)
@Illustrate( {
Illustrate.Feature.annotation,
Illustrate.Feature.enumeration } )
public @interface Illustrate {
enum Feature {
annotation, enumeration, forLoop,
generics, autoboxing, varargs;
@Illustrate(
{Illustrate.Feature.enumeration,Illustrate.Feature.forLoop})
public class Suggester {
// @SuppressWarnings({"unchecked"}) // not yet supported
public static void main( String[] args ) {
try {
java.util.Scanner userInput =
new java.util.Scanner( System.in );
System.out.print( "In what class are you interested? " );
Class theClass = Class.forName( userInput.next() );
Illustrate ill =
(Illustrate)theClass.getAnnotation( Illustrate.class);
We enable you to leverage knowledge
181
anytime, anywhere!
if ( ill != null ) {
System.out.println( "Look at this class if you'd " +
" like to see examples of" );
for ( Illustrate.Feature f : ill.value() ) {
System.out.println( "\t" + f );
}
}
else {
System.out.println(
"That class will teach you nothing." );
}
}
catch( ClassNotFoundException cnfe ) {
System.err.println( "I could not find a class named \"" +
cnfe.getMessage() + "\"." );
System.err.println( "Are you sure about that name?" );
}
} }
• java Suggester
In what class are you interested? Suggester
Look at this class if you'd like to see examples of
the enumeration feature
the forLoop feature
• java Suggester
In what class are you interested? Illustrate
Look at this class if you'd like to see examples of
the annotation feature
the enumeration feature
http://www.eclipse.org/aspectj/doc/released/adk15notebook/an
notations.html
http://www-128.ibm.com/developerworks/library/j-annotate1/
http://www-128.ibm.com/developerworks/library/j-
annotate2.html
http://www.softwaresummit.com/2004/speakers/LandersAnnot
ations.pdf
http://java.sun.com/mailers/techtips/corejava/2006/tt0620.html
We enable you to leverage knowledge
186
anytime, anywhere!
Summary
In this course, following topics were covered:-
• Multithreading
• Concurrency
• Input Output Streams & Serialization
• JDBC
• Java Beans
• Generics
• Annotations