0% found this document useful (0 votes)
34 views

Android 100%

The document discusses advanced Java programming concepts like generics. Generics allow type safety and avoid casts by using type parameters. Key topics covered include generic types, type parameter bounds, and examples of using generics with collections and for calculating statistics.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

Android 100%

The document discusses advanced Java programming concepts like generics. Generics allow type safety and avoid casts by using type parameters. Key topics covered include generic types, type parameter bounds, and examples of using generics with collections and for calculating statistics.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

Advanced programming in Java

Overview
Advanced
Generics
programming in Java

 Java Collections Framework
 Reflection
Ing. Marek Běhálek
katedra informatiky FEI VŠB-TUO
 Annotations
A-1018 / 597 324 251  Serializations
http://www.cs.vsb.cz/behalek  Streams in Java
[email protected]  Thread and Synchronization

Advanced programming in Java

Generics - What Generics in


Generics - Compare Java are?
List li = new ArrayList();  A way to control a class type definitions.
li.add(new Integer(1));  Otherwise known as parameterised types or
Integer x = (Integer)li.get(0); templates.
 A way of improving the clarity of code
List<Integer> li = new ArrayList<Integer>();  A way of avoiding (casts) in code, turning run-
li.add(new Integer(1)); time errors (typically ClassCastException) into
Integer x = li.get(0); compile-time errors. This is A Good Thing.
 Benefits of generic types
 increased expressive power
 The main point: “old” containers hold “Object” objects  improved type safety
and need casts which are problematic because:  explicit type parameters and implicit type casts
 Cast is something the programmer thinks is true at a
single point.
 Only in Java 5 and above
 Generic type is true everywhere.
Advanced programming in Java Advanced programming in Java

(c) Marek Běhálek, Katedra informatiky FEI VŠB-TU Ostrava 1


Advanced programming in Java

Generics – Definition of Generics – Type parameter


Generics bounds
interface Collection<A> { public interface Comparable<T> { public int compareTo(T arg); }
public void add (A x);
public Iterator<A> iterator (); public class TreeMap<K extends Comparable<K>,V> {
}
private static class Entry<K,V> { ... }
class LinkedList<A> implements Collection<A> {
private Entry<K,V> getEntry(K key) {
protected class Node {
A elt; while (p != null) {
Node next = null; int cmp = k.compareTo(p.key);
Node (A elt) { this.elt = elt; } …}
} …
... }
} …
 type variable = "placeholder" for an unknown type
 similar to a type, but not really a type
 bounds = super-type of a type variable
 several restrictions  purpose: make available non-static methods of a type variable
 not allowed in new expressions, cannot be derived from, no class literal, ...  limitations: gives no access to constructors or static methods

Advanced programming in Java Advanced programming in Java

Generics – Generics and sub- Generics – Example: Statistics


typing class
 Should this be valid? •This class gets an array of numbers and calculates
their average.
List<String> ls = new ArrayList<String>(); public class Stats<T> {
List<Object> lo = ls; T[] nums; // nums is an array of type T
//… Stats(T[] o) {
lo.add(new Object()); nums = o;
}
String s = ls.get(0);
// Return type double in all cases.
double average() {
 In other words: is List<String> a subtype of double sum = 0.0;
List<Object> ?
for(int i=0; i < nums.length; i++)
 The answer is NO! sum += nums[i].doubleValue(); // Error!!!
 But inheritance is a powerful tool, and we want }
return sum / nums.length;
to use it with generics… }

Advanced programming in Java Advanced programming in Java

(c) Marek Běhálek, Katedra informatiky FEI VŠB-TU Ostrava 2


Advanced programming in Java

Generics – Example: Statistics Generics - Using generic types


class (1)
•To solve the problem we will use a bounded type.
 Can use generic types with or without type
public class Stats <T extends Number> {
Number argument specification
T[] nums; // nums is an array of type T
Stats(T[] o) {
 with concrete type arguments
nums = o;
}  concrete instantiation
// Return type double in all cases.
Integer Double  without type arguments
double average() {
double sum = 0.0;  raw type
Long
for(int i=0; i < nums.length; i++)
sum += nums[i].doubleValue(); // now it’s OK.  with wildcard arguments
return sum / nums.length;  wildcard instantiation
}
}

Advanced programming in Java Advanced programming in Java

Generics - Using generic types


(2) Generics – Wildcards (1)
 Concrete instantiation  What is the problem with this code?
 type argument is a concrete type
void printCollection( Collection<Object> c){
void printDirectoryNames(Collection<File> files) { for (Object o : c)
for (File f : files) System.out.println(o);
if (f.isDirectory()) }
System.out.println(f);
}  Collection<Object> is NOT a supertype of any other collection.
 this code is not so usefull…
 more expressive type information  The solution: wildcards:
 enables compile-time type checks
 Raw type void printCollection( Collection<?> c){
 no type argument specified for (Object o : c)
 permitted for compatibility reasons System.out.println(o);
 permits mix of non-generic (legacy) code with generic code
}
Advanced programming in Java Advanced programming in Java

(c) Marek Běhálek, Katedra informatiky FEI VŠB-TU Ostrava 3


Advanced programming in Java

Generics - Bounded wildcard,


Generics – Wildcards (2) Stats revisited
public class Stats{
 A wildcard denotes a representative from a
static double average(List<? extends Number> nums) {
family of types double sum = 0.0;

 unbounded wildcard - ? for (Number num : nums)


sum += num.doubleValue();
 all types
return sum / nums.size();
 lower-bound wildcard - ? extends Supertype }

 all types that are subtypes of Supertype public static void main(String args[]) {
Integer inums[] = { 1, 2, 3, 4, 5 };
 upper-bound wildcard - ? super Subtype //List<Number> li1 = Arrays.asList(inums); //compilation error
//List<? extends Number> li2 = Arrays.asList(inums); //ok
 all types that are supertypes of Subtype List<Integer> li = Arrays.asList(inums);
System.out.println(average(li)); //prints 3.0 }
}

Advanced programming in Java Advanced programming in Java

Generics – Calculating the


Generics – Generic methods median
 the avarage() method signature: public class Stats{
static double average(List<? Extends number> nums) { …}

static double average(List<? extends Number> nums) static <T extends Number> T median(List<T> nums) {
int pos = nums.size()/2;
return nums.get(pos);
}
 An alternative (equivalent) signature: public static void main(String args[]) {
Integer inums[] = { 0, 0, 0, 0, 100};
List<Integer> li = Arrays.asList(inums);
static <T extends Number> double average(List<T> nums) System.out.println(average(li));
System.out.println(median(li));
}
}
 The later is called a generic method.
 Which is better?
 When there are no dependencies between the method
parameters - use wildcards. This way the compiler knows about the dependency
between the input and output arguments.
Advanced programming in Java Advanced programming in Java

(c) Marek Běhálek, Katedra informatiky FEI VŠB-TU Ostrava 4


Advanced programming in Java

Generics – Another generic Generics – Java Generics


method examples Implemetation
Determine if an object is in an array:  There are two general approaches:
 Code specialisation – generate a version of the class for each
static <T, V extends T> boolean isIn(V x, T[] y) { way it‟s used (what C++ does)
 Code sharing – use a single version of the class for all uses, but
for(int i=0; i < y.length; i++)
perform checks as each use occurs (what Java does)
if(y[i].equals(x)) return true;
 The Java compiler uses type erasure to (effectively)
return false; translate generic code into pre-generic code by:
}  Replacing every use of a formal type parameter by a use of the
most general type it could be in context (trivially, Object)
Collections.sort()  This means that code compiled with Java 5 can be run
by a Java 1.4 Virtual machine – there‟s no change to
public static <T extends Comparable<? super T>> void sort(List<T> list) {
… the Java bytecode.
}
Advanced programming in Java Advanced programming in Java

Generics – What will be the Generics – Generic usage


value of res? mistakes
List <String> l1 = new ArrayList<String>(); class MyGenClass<T, V> { class Gen<T> {
List<Integer> l2 = new ArrayList<Integer>(); T ob1; T ob;
V ob2; Gen() {
Boolean res = (l1.getClass() == l2.getClass()); //Can't create an instance of T...

// These two overloaded methods


ob = new T();
are ambiguous... }
void set(T o) { }
ob1 = o;
public class Wrong<T> {
} // Wrong, no static variables of type T.

Answer: true static T ob;


void set(V o) {
Explanation: after erasure both l1 ans l2 ob2 = o; // Wrong, no static method can use T .
static T getob() {
have the run-time type ArrayList }
return ob;
}
}
Advanced programming in Java Advanced programming in Java

(c) Marek Běhálek, Katedra informatiky FEI VŠB-TU Ostrava 5


Advanced programming in Java

Generics – What will be Collection Framework –


printed? General Description
class Gen<T> {
T ob;  A collection (called a container in C++) is an
Gen(T o) { ob = o; }
object that groups multiple elements into a
T showType() {
println("Type of T is “+ob.getClass().getName() );
single unit.
for (Method meth : this.getClass().getDeclaredMethods())
println(meth.toString());
 Collections are used to store, retrieve and
}
return ob; manipulate data, and to transmit data from
one method to another.
public static void main(String args[]) {
Gen<Integer> iOb = new Gen<Integer>(88);
//String s = iOb.showType(); //compilation error...
 Collections hold:
Integer i= iOb.showType();  a specific data type;
}
} Answer:
Type of T is java.lang.Integer
 a generic data type.
java.lang.ObjectGen.showType()
Advanced programming in Java Advanced programming in Java

Collection Framework – Collection Framework – Why


General Description Use It?
 A collections framework is a unified architecture  There are many benefits to using the Java
for representing and manipulating collections. It
has: Collections Framework:
 Interfaces: abstract data types representing collections  Reduces programming effort.
 Allow collections to be manipulated independently of the
details of their representation.  Increases program speed and quality.
 Implementations: concrete implementations of the  Allows interoperability among unrelated APIs.
collection interfaces
 Reusable data structures  Reduces the effort to learn and use new APIs.
 Algorithms: methods that perform useful  Reduces effort to design new APIs.
computations, such as searching and sorting
 These algorithms are said to be polymorphic: the same  Fosters software reuse.
method can be used on different implementations.
 Reusable functionality
Advanced programming in Java Advanced programming in Java

(c) Marek Běhálek, Katedra informatiky FEI VŠB-TU Ostrava 6


Advanced programming in Java

Collection Framework – Collection Framework –


Interfaces Collections Interfaces
 An interface describes a set of methods:
 no constructors or instance variables
 Interfaces must be implemented by classes
 2 or more classes implement an interface
 Classes guaranteed to have the same methods Queue
 Objects can be treated as the same type since Java 5

 Can use different algorithms / instance variables

 Collection is actually an interface


Advanced programming in Java Advanced programming in Java

Collection Framework – Collection Framework –


Collection Interfaces Algorithms
Collection - a group of objects, called elements

 Set - an unordered collection with no duplicates  Java has polymorphic algorithms to provide

 SortedSet - an ordered collection with no duplicates
List - an ordered collection, duplicates are allowed
functionality for different types of
 Queue -linear sequence of items “for processing” collections
 Can add an item to the queue
 Can “get the next item”from the queue  Sorting (e.g. sort)
 What is “next”depends on queue implementation
 Map - a collection that maps keys to values  Shuffling (e.g. shuffle)
SortedMap - a collection ordered by the keys

 Routine Data Manipulation (e.g. reverse, addAll)
 Note
 Some collections requires elements to be comparable  Searching (e.g. binarySearch)
 Must be able to say an element is “less than”or “greater than”another
element  Composition (e.g. frequency)
 There are are two distinct hierarchies
 We can use generics!  Finding Extreme Values (e.g. max)
Advanced programming in Java Advanced programming in Java

(c) Marek Běhálek, Katedra informatiky FEI VŠB-TU Ostrava 7


Advanced programming in Java

Collection Framework – Collection Framework –


Implementation (1) Implementation (2)
 Multiple implementations of each interface  A collection class
 implements an ADT as a Java class
 All provide same basic functionality  can be instantiated
 Different storage requirements  Java implements interfaces with
 List: ArrayList, LinkedList, Vector, Stack…
 Different performance characteristics  Map: HashMap, TreeMap…
 Sometimes other enhancements too  Set: TreeSet, HashSet…
 Queue: PriorityQueue
 e.g. additional operations not part of the interface  All Collection implementations should have two
 Java API Documentation gives the details! constructors:
 A no-argument constructor to create an empty collection
 See interface API Docs for list of implementers  A constructor with another Collection as argument
 Read API Docs of implementations for  If you implement your own Collection type, this rule cannot be
enforced, because an Interface cannot specify constructors
performance and storage details
Advanced programming in Java Advanced programming in Java

Collection Framework –Collections


and Java 1.5 Generics Iterable<E> Iterator<E>

 Up to Java 1.4, collections only stored Objects Collection<E> ListIerator<E>


LinkedList points = new LinkedList();
points.add(new Point(3, 5)); Set<E> Queue<E> List<E>
Point p = (Point) points.get(0);
SortedSet<E> EnumSet<E> ArrayList<E>
 Casting everything gets annoying. PriorityQueue<E>
 Could add non-Point objects to points collection too! HashSet<E> LinkedList<E>
TreeSet<E>
 Java 1.5 introduces generics
LinkedHashSet<E>
LinkedList<Point> points = new LinkedList<Point>();
Map<K,V>
points.add(new Point(3, 5));
Point p = points.get(0); EnumMap<K,V>

WeakHashMap<K,V>
 No more need for casting. SortedMap<K,V>
 Can only add Point objects to points too. HashMap<E>
 Type checking at a compile time.
TreeMap<K,V>
LinkedHashMap<K,V>
Advanced programming in Java Advanced programming in Java

(c) Marek Běhálek, Katedra informatiky FEI VŠB-TU Ostrava 8


Advanced programming in Java

Collection Framework – The Collection Framework – Collection


Collection Interface Classes
 The Collection Interface String[] strings = new  Classes in Sets:  Class in Queues:
String[collection.size()];
 The basis of much of the collection  HashSet<T>  FIFO ordering
strings =
system is the Collection interface. collection.toArray(strings);  LinkedHashSet<T>  PriorityQueue<T>
 TreeSet<T>  Classes in Maps:
 Methods: String[] strings =  EnumSet<T extends Enum<T>>  Does not extend Collection
collection.toArray(new because it has a contract that is
 public int size() String[0]); different in important ways: do
 public boolean isEmpty()  Classes in Lists: not add an element to a Map(add
public boolean contains(Object elem)  public boolean a key/value pair), and a Map

containsAll(Collection<?>  To define a collection whose
 public Iterator<E> iterator() coll) elements have a defined allows looking up.
public boolean order-each element exists in a  Hashtable<K,V>
 public Object[] toArray() 
addAll(Collection<? extends praticular poistion the  HashMap<K,V>
 public <T> T[] toArray(T[] dest) E> coll) collection.  LinkedHashMap<K,V>
 public boolean add(E elem)  public boolean Vector<T>
removeAll(Collection<?> coll)   WeakHashMap<K,V>
 public boolean remove(Object elem)  Stack<T> IdentityHashMap<K,V>
 public boolean 
retainAll(Collection<?> coll)  LinkedList<T>  TreeMap<K,V> : keeping its keys
 public void clear()  ArrayList<T> sorted in the same way as TreeSet

Advanced programming in Java Advanced programming in Java

Collection Framework – Collection Framework – Using


Collections of Objects (1) Collections
 Sequences  Lists and sets are easy:
HashSet<String> wordList = new HashSet<String>();
 The objects are stored in a linear fashion, not necessarily
LinkedList<Point> waypoints = new LinkedList<Point>();
in any particular order, but in an arbitrary fixed sequence
with a beginning and an end.
 Element type must appear in both variable declaration and in
 Collections generally have the capability to expand to new-expression.
accommodate as many elements as necessary.
 Maps  Maps are more verbose:
 Each entry in the collection involves a pair of objects. TreeMap<String, WordDefinition> dictionary =
new TreeMap<String, WordDefinition>();
 A map is also referred to sometimes as a dictionary.
 Each object that is stored in a map has an associated key  First type is key type, second is the value type.
object, and the object and its key are stored together as  See Java API Docs for available operations
a “name-value” pair.

Advanced programming in Java Advanced programming in Java

(c) Marek Běhálek, Katedra informatiky FEI VŠB-TU Ostrava 9


Advanced programming in Java

Collection Framework – Collection Framework –


Iteration Over Collections Iteration Over Collections (2)
 Often want to iterate over values in collection.  Collections provide an iterator() method
ArrayList collections are easy:  Returns an iterator for traversing the collection
ArrayList<String> quotes;
...  Example:
for (int i = 0; i < quotes.size(); i++)
System.out.println(quotes.get(i)); HashSet<Player> players;
...
Iterator<Player> iter = players.iterator();
 Impossible/undesirable for other collections!
 Iteratorsare used to traverse contents while (iter.hasNext()) {
Player p = iter.next();
 Iterator is another simple interface:
... // Do something with p
 hasNext() –Returns true if can call next()
}
 next() –Returns next element in the collection
 ListIterator extends Iterator  Iterator should also use generics
 Provides many additional features over Iterator
 Can use iterator to delete current element, etc.
Advanced programming in Java Advanced programming in Java

Collection Framework –Java Collection Framework – Iterators and


1.5 Enhanced For-Loop Syntax ListIterators
 Setting up and using an iterator is annoying  Iterator<E> interface public void removeLongStrings
 T next() (Collection<? Extends String> coll, int maxLen) {
 Java 1.5 introduces syntactic sugar for this:  boolean hasNext()
Iterator<? Extends String> it = coll.iterator();
for (Player p : players) {  void remove()
while (it.hasNext()) {
String str = it.next();
... // Do something with p
if (Str.length() > maxLen) it.remove();
}  ListIterator<E> interface }
 Can‟t access actual iterator used in loop.  extends Iterator }
 Best for simple scans over a collection‟s contents  T next()
 boolean hasNext()
 int nextIndex()
 Can also use enhanced for-loop syntax with arrays:  T previous()
ListIterator<String> it = list.listIterator(list.size());
while (it.hasPrevious()) {
float sum(float[] values) {  boolean hasPrevious() String obj = it.previous();
float result = 0.0f;  int previousIndex() System.out.println(obj);
for (float val : values) result += val;  void remove() // … use obj ….
 void add(T obj) }
return result;
}  void set(T obj)

Advanced programming in Java Advanced programming in Java

(c) Marek Běhálek, Katedra informatiky FEI VŠB-TU Ostrava 10


Advanced programming in Java

Collection Framework – Collection Framework –


Collection Algorithms Collection Elements (1)
 java.util.Collections class provides some common algorithms  Collection elements may require certain
…not to be confused with Collection interface

 Algorithms are provided as static functions.
capabilities.
 Implementations are fast, efficient, and generic.  List elements don‟t need anything special
 …unless contains(), remove(), etc. are used!
 Example: sorting  Then, elements should provide a correct equals()
LinkedList<Product> groceries;
implementation
...
Collections.sort(groceries);  Requirements for equals():
 a.equals(a) returns true
 Collection is sorted in-place: groceriesis changed
 a.equals(b) same as b.equals(a)
 Read Java API Docs for more details  If a.equals(b)is true and b.equals(c)is true, then
 Also see Arrays class for array algorithms a.equals(c)is also true
 a.equals(null)returns false
Advanced programming in Java Advanced programming in Java

Collection Framework – Collection Framework –


Collection Elements (2) Implementing hashCode(1)
 Sets and maps require special features  Is this a correct implementation?
 Sets require these operations on set-elements
 Maps require these operations on the keys public int hashCode() {
return 42;
 equals() must definitely work correctly }

 TreeSet, TreeMap require sorting capability  It satisfies the rules, so technically yes…
 Element or key class must implement java.lang.Comparable interface  In practice, will cause programs to be very inefficient.
 Or, an appropriate implementation of java.util.Comparator must be
provided
 Hash function should generate a wide range of values.
 Specifically, should produce a uniform distribution of values.
 HashSet, HashMap require hashing capability  Facilitates most efficient operation of hash tables.
 Element or key class must provide a good implementation of  Requirement is that equal objects must produce identical hash values…
Object.hashCode()
 Also good if unequal objects produce different hash values.

Advanced programming in Java Advanced programming in Java

(c) Marek Běhálek, Katedra informatiky FEI VŠB-TU Ostrava 11


Advanced programming in Java

Collection Framework – Collection Framework –Comparing


Implementing hashCode(2) and Ordering Objects
 A few basic hints:  Objects implement java.lang.Comparable<T>interface to
allow them to be ordered
 If field is a boolean, use 0 or 1 for hash code  public int compareTo(T obj)
 If field is an integer type, cast value to int  Returns a value that imposes an order:
 result < 0 means thisis less than obj
 If field is a non-array object type:  result == 0 means thisis “same as”obj
 Call the object‟s hashCode() function, or use 0 for  result > 0 means thisis greater than obj
null  This defines the natural orderingof a class
i.e. the “usual”or “most reasonable”sort-order
If field is an array:


 Natural ordering should be consistent with
 Include every array-element into final hash  equals()
value!  a.compareTo(b)returns 0 only when a.equals(b)is true
 If computing the hash is expensive, cache it.
 Implement this interface correctly for using TreeSet/ TreeMap
 Must re-compute hash value if object changes!
Advanced programming in Java Advanced programming in Java

Collection Framework – Reflection – Java looking at


Alternate Orderings Java
 Can provide extra comparison functions.  One of the unusual capabilities of Java is that a program can
examine itself
 Provide a separate object that implements  You can determine the class of an object
java.util.Comparator<T> interface
 You can find out all about a class: its access modifiers, superclass,
 Simple interface: fields, constructors, and methods
 int compare(T o1, T o2)  You can find out what is in an interface
 Sorted collections, sort algorithms can also take a  Even if you don’t know the names of things when you write the
program, you can:
comparator object.  Create an instance of a class
 Allows sorting by all kinds of things!  Get and set instance variables

 Comparator implementations are typically nested  Invoke a method on an object

classes  Create and manipulate arrays


 In “normal” programs you don’t need reflection
 e.g. Playerclass could provide a ScoreComparator nested
class  You do need reflection if you are working with programs that
process programs
 Debugger
Advanced programming in Java Advanced programming in Java

(c) Marek Běhálek, Katedra informatiky FEI VŠB-TU Ostrava 12


Advanced programming in Java

Reflection – Introspection Reflection – The Class class


 Introspection is a programmatic facility built on top of  To find out about a class, first get its Class object
reflection and a few supplemental specifications (see the
 If you have an object obj, you can get its class object
java.beans package).
 It provides somewhat higher-level information about a class with
than does reflection. Class c = obj.getClass();
 Introspection makes general class information available at run-  You can get the class object for the superclass of a Class c
time with
 The type (class) does not have to be known at compile time Class sup = c.getSuperclass();
 E.g. list the attributes of an object
 If you know the name of a class (say, Button) at compile
 This is very useful in time, you can get its class object with
 Rapid Application Development (RAD)
 Visual approach to GUI development
Class c = Button.class;
 Requires information about component at run-time  If you know the name of a class at run time (in a String
JavaBeans

variable str), you can get its class object with
 Remote Method Invocation (RMI)
 Distributed objects
Class c = class.forName(str);
Advanced programming in Java Advanced programming in Java

Reflection – Getting the class Reflection – Getting all the


name superclasses
 If you have a class object c, you can get the  getSuperclass() returns a Class object (or null if you call it on
Object, which has no superclass)
name of the class with c.getName()  The following code is from the Sun tutorial:
 getName returns the fully qualified name; that static void printSuperclasses(Object o) {
is, Class subclass = o.getClass();
Class c = Button.class; Class superclass = subclass.getSuperclass();
String s = c.getName(); while (superclass != null) {
System.out.println(s); String className = superclass.getName();
will print System.out.println(className);
java.awt.Button subclass = superclass;
 Class Class and its methods are in java.lang, superclass = subclass.getSuperclass();
}
which is always imported and available }

Advanced programming in Java Advanced programming in Java

(c) Marek Běhálek, Katedra informatiky FEI VŠB-TU Ostrava 13


Advanced programming in Java

Reflection – Getting the class Reflection – Getting the class


modifiers(1) modifiers (2)
 The modifiers (e.g., public, final, abstract etc.)  Modifier contains these methods (among
of a Class object is encoded in an int and can others):
be queried by the method getModifiers().  public static boolean isAbstract(int)
 To decode the int result, we need methods of  public static boolean isFinal(int)
the Modifier class, which is in java.lang.reflect,  public static boolean isInterface(int)
so:  public static boolean isPrivate(int)
import java.lang.reflect.*;  public static boolean isProtected(int)
 Then we can do things like:  public static boolean isPublic(int)
if (Modifier.isPublic(m))  public static String toString(int)
System.out.println("public");  This will return a string such as
"public final synchronized strictfp"
Advanced programming in Java Advanced programming in Java

Reflection – Getting interfaces Reflection – Getting Fields


 A class can implement zero or more interfaces  public Field[] getFields() throws SecurityException
 getInterfaces() returns an array of Class objects
 Returns an array of public Fields (including inherited
static void printInterfaceNames(Object o) { fields).
Class c = o.getClass();  The length of the array may be zero
Class[] theInterfaces = c.getInterfaces();
 The fields are not returned in any particular order
for (Class inf: interfaces) {
System.out.println(inf.getName()); }}  Both locally defined and inherited instance variables are
returned, but not static variables.
 The class Class represents both classes and interfaces
 public Field getField(String name)
 To determine if a given Class object c is an interface, use
c.isInterface() throws NoSuchFieldException, SecurityException
 To find out more about a class object, use:  Returns the named public Field
 getModifiers(), getFields() // "fields" == "instance variables“,  If no immediate field is found, the superclasses and
getConstructors(), getMethods(), isArray() interfaces are searched recursively

Advanced programming in Java Advanced programming in Java

(c) Marek Běhálek, Katedra informatiky FEI VŠB-TU Ostrava 14


Advanced programming in Java

Reflection – Getting
Reflection – Using Fields Constructors of a class
 If f is a Field object, then  if c is a Class, then
 c.getConstructors() : Constructor[] return an array of all
 f.getName() returns the simple name of the field public constructors of class c.
 f.getType() returns the type (Class) of the field  c.getConstructor( Class … paramTypes ) returns a
 f.getModifiers() returns the Modifiers of the field constructor whose parameter types match those given
paramTypes.
 f.toString() returns a String containing access
Ex:
modifiers, the type, and the fully qualified field
 String.class.getConstructors().length
name
> 15;
 Example: public java.lang.String Person.name
 String.class.getConstrucor( char[].class, int.class,
 f.getDeclaringClass() returns the Class in which int.class).toString()
this field is declared > String(char[], int,int).
 note: getFields() may return superclass fields.
Advanced programming in Java Advanced programming in Java

Reflection – Constructors Reflection – Example


 If c is a Constructor object, then  Constructor c = String.class.getConstrucor(
 c.getName() returns the name of the constructor, as
a String (this is the same as the name of the class) char[].class, int.class, int.class).toString()
 c.getDeclaringClass() returns the Class in which this
constructor is declared
 c.getModifiers() returns the Modifiers of the
 String(char[], int,int).
constructor
 c.getParameterTypes() returns an array of Class
objects, in declaration order  String s = c.newInstance(
 c.newInstance(Object… initargs) creates and returns new char[] {„a‟,‟b‟,‟c‟,‟d‟ }, 1, 2
a new instance of class c );
 Arguments that should be primitives are automatically
unwrapped as needed  assert s == “bc”;
Advanced programming in Java Advanced programming in Java

(c) Marek Běhálek, Katedra informatiky FEI VŠB-TU Ostrava 15


Advanced programming in Java

Reflection – Method methods


Reflection – Methods (1)
 public Method[] getMethods()  getDeclaringClass()
 Returns the Class object representing the class or
throws SecurityException interface that declares the method represented by this
 Returns an array of Method objects Method object
 getName()
 These are the public member methods of the  Returns the name of the method represented by this
class or interface, including inherited methods Method object, as a String
 The methods are returned in no particular order  getModifiers()
 Returns the Java language modifiers for the method
 public Method getMethod(String name, represented by this Method object, as an integer
Class… parameterTypes)  getParameterTypes()
throws NoSuchMethodException, SecurityException  Returns an array of Class objects that represent the
formal parameter types, in declaration order, of the
method represented by this Method object
Advanced programming in Java Advanced programming in Java

Reflection – Method methods Reflection – Examples of


(2) invoke()
 getReturnType()  “abcdefg”.length()
 Returns a Class object that represents the formal return > 7
type of the method represented by this Method object
 Method lengthMethod = String.class.getMethod(“length”) ;
 toString()
 lengthMethod.invoke(“abcdefg”)
 Returns a String describing this Method (typically pretty
long) >7
 public Object invoke(Object obj, Object… args)  “abcdefg”.substring(2, 5)

 Invokes the underlying method represented by this > cde


Method object, on the specified object with the specified  Method substringMethod = String.class.getMethod (
parameters “substring”, int.class, Integer.TYPE ) ;
 Individual parameters are automatically unwrapped to
 substringEMthod.invoke( “abcdefg”, 2, new Integer(5) )
match primitive formal parameters
> cde
Advanced programming in Java Advanced programming in Java

(c) Marek Běhálek, Katedra informatiky FEI VŠB-TU Ostrava 16


Advanced programming in Java

Reflection – Arrays (1) Reflection – Arrays (2)


 To determine whether an object obj is an  The Array class in java.lang.reflect provides static methods
array, for working with arrays
 Get its class c with Class c = obj.getClass();  To create an array,
 Test with c.isArray()  Array.newInstance(Class componentType, int size)
 To find the type of components of the array,  This returns, as an Object, the newly created array
 c.getComponentType()  You can cast it to the desired type if you like
 Returns null if c is not the class of an array  The componentType may itself be an array
 Ex:  This would create a multiple-dimensioned array
 int[].class.isArray() == true ;  The limit on the number of dimensions is usually 255
Array.newInstance(Class componentType, int… sizes)
 int[].class.getComponentType() ==

int.class  This returns, as an Object, the newly created


multidimensional array (with sizes.length dimensions)

Advanced programming in Java Advanced programming in Java

Reflection – Getting non-public


Reflection – Examples members of a class

 a = new int[] {1,2,3,4};  All getXXX() methods of Class mentioned above return only
public members of the target (as well as ancestor ) classes,
 Array.getInt(a, 2) //  3 but they cannot return non-public members.
 Array.setInt(a, 3, 5 ) // a = {1,2,3, 5 }.  There are another set of getDeclaredXXX() methods in Class
that will return all (even private or static ) members of
target class but no inherited members are included.
getDeclaredConstructors(), defDeclaredConstrucor(Class…)
 s = new String[] { “ab”, “bc”, “cd” }; 

 getDeclaredFields(),
 Array.get(s, 1 ) //  “bc” getDeclaredField(String)
 Array.set(s, 1, “xxx”) // s[1] = “xxx”  getDeclaredmethods(),
getDeclaredMethod(String, Class…)

Advanced programming in Java Advanced programming in Java

(c) Marek Běhálek, Katedra informatiky FEI VŠB-TU Ostrava 17


Advanced programming in Java

Reflection – Example Annotations – History


 String.class.getConstructors().length  The Java platform has always had various ad hoc
> 15 annotation mechanisms
 String.class.getDeclaredConstructors().length  Javadoc annotations
/**
> 16. * Locate a value in a
* collection.
 Constructor[] cs = * @param value the sought-after value

String.class.getDeclaredConstructors(); * @return the index location of the value


* @throws NotFoundException

for(Constructor c : cs) */
int search( Object value ) { …

if( ! (Modifier.isPublic(c.getModifiers())))  @transient - an ad hoc annotation indicating that a field


out.println(c); should be ignored by the serialization subsystem
@deprecated - an ad hoc annotation indicating that the
> java.lang.String(int,int,char[]) // package 

method should no longer be used


Advanced programming in Java Advanced programming in Java

Annotations – Introduction Annotations – Usage


 Annotations provide data about a program that is not  Annotations have a number of uses, among
part of the program itself. An annotation is an
attribute of a program element. them:
 As of release 5.0, the platform has a general purpose  Information for the compiler - Annotations can be
annotation (metadata) facility that permits to define used by the compiler to detect errors or suppress
and use your own annotation types. warnings
 The facility consists of:  Compiler-time and deployment-time processing -
 a syntax for declaring annotation types Software tools can process annotation information to
 a syntax for annotating declarations generate code, XML files, and so forth
 APIs for reading annotations
 a class file representation for annotations  Runtime processing - Some annotations are
 an annotation processing tool available to be examined at runtime (reflection)
Advanced programming in Java Advanced programming in Java

(c) Marek Běhálek, Katedra informatiky FEI VŠB-TU Ostrava 18


Advanced programming in Java

Annotations – Annotation Type Annotations – Annotation Type


Declaration (1) Declaration (2)
 Similar to normal interface declarations:  Method declarations should not have any
public @interface RequestForEnhancement {
int id();
parameters
String synopsis();
String engineer() default "[unassigned]";
 Method declarations should not have any throws
}
String date(); default "[unimplemented]";
clauses
 An at-sign @ precedes the interface keyword
 Return types of the method should be one of
the following:
 Each method declaration defines an element of the
 primitives, String, Class, enum, array of the above
annotation type
types public @interface RequestForEnhancement {
 Methods can have default values int id();
String synopsis();
 Once an annotation type is defined, you can use it to String engineer() default "[unassigned]";
String date(); default "[unimplemented]";
annotate declarations }

Advanced programming in Java Advanced programming in Java

Annotations – Annotating Annotations – Annotating


Declarations (1) Declarations (2)
 Syntactically, the annotation is placed in front of the  In annotations with a single element, the element
program element's declaration, similar to static or should be named value:
final or protected
public @interface Copyright {
@RequestForEnhancement( String value();
id = 2868724, }
synopsis = "Enable time-travel",
engineer = "Mr. Peabody",  It is permissible to omit the element name and equals
)
date = "4/1/3007"
sign (=) in a single-element annotation:
public static void travelThroughTime(Date destination) { ... } @Copyright("2002 Yoyodyne Propulsion Systems")
public class OscillationOverthruster { ... }
 An annotation instance consists of
 the "@" sign  If no values, then no parentheses needed:
 the annotation name public @interface Preliminary { }
 a parenthesized list of name-value pairs
@Preliminary public class TimeTravel { ... }

Advanced programming in Java Advanced programming in Java

(c) Marek Běhálek, Katedra informatiky FEI VŠB-TU Ostrava 19


Advanced programming in Java

Annotations – What can be Annotations – Annotations


annotated? Used by the Compiler
Annotatable program elements:  There are three annotation types that are
 package predefined by the language specification itself:
 class, including
 @Deprecated - indicates that the marked element is
 interface
deprecated and should no longer be used
 enum
 method  @Override - informs the compiler that the element is
 field meant to override an element declared in a superclass
 only at compile time  @SuppressWarnings - tells the compiler to suppress
 local variable specific warnings that it would otherwise generate
 formal parameter

Advanced programming in Java Advanced programming in Java

Annotations – Annotation
Annotations – Meta-Annotations Processing
 Meta-annotations - types designed for annotating  It's possible to read a Java program and take actions based
annotation-type declarations (annotations-of-annotations) on its annotations
 To make annotation information available at runtime, the
 Meta-annotations: annotation type itself must be annotated with
 @Target - indicates the targeted elements of a class in which the @Retention(RetentionPolicy.RUNTIME):
annotation type will be applicable
@Retention(RetentionPolicy.RUNTIME)
 TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, etc @interface AnnotationForRuntime
{
 @Retention - how long the element holds onto its annotation // Elements that give information for runtime processing
 SOURCE, CLASS, RUNTIME }

 @Documented - indicates that an annotation with this type should  Annotation data can be examined using reflection
be documented by the javadoc tool mechanism, see e.g. java.lang.reflect.AccessibleObject:
 <T extends Annotation> T getAnnotation(Class<T>)
 @Inherited - indicates that the annotated class with this type is  Annotation[] getAnnotations()
automatically inherited  boolean isAnnotationsPresent(<Class<? extends Annotation>)

Advanced programming in Java Advanced programming in Java

(c) Marek Běhálek, Katedra informatiky FEI VŠB-TU Ostrava 20


Advanced programming in Java

Annotations – Class Annotation


Annotations – Bigger Example Example
@Retention(value=RetentionPolicy.RUNTIME)
 The following example shows a program that @Illustrate( {
pokes at classes to see "if they illustrate Illustrate.Feature.annotation,
Illustrate.Feature.enumeration } )
anything" public @interface Illustrate {
enum Feature {
 Things to note in example: annotation, enumeration, forLoop,
generics, autoboxing, varargs;
 An annotation may be annotated with itself
@Override public String toString() {
 How annotations meta-annotated with return "the " + name() + " feature";
Retention(RUNTIME) can be accessed via }
};
reflection mechanisms Feature[] value() default {Feature.annotation};
}

Advanced programming in Java Advanced programming in Java

import java.lang.annotation.Annotation; if ( ill != null ) {


System.out.println( "Look at this class if you'd " +
@Author(@Name(first="James",last="Heliotis")) " like to see examples of" );
@Illustrate( for ( Illustrate.Feature f : ill.value() ) {
{Illustrate.Feature.enumeration,Illustrate.Feature.forLoop}) System.out.println( "\t" + f );
public class Suggester { }
@SuppressWarnings({"unchecked"}) // not yet supported }
public static void main( String[] args ) { else {
try { System.out.println(
java.util.Scanner userInput = "That class will teach you nothing." );
new java.util.Scanner( System.in ); }
System.out.print( "In what class are you interested? " ); }
Class theClass = Class.forName( userInput.next() ); catch( ClassNotFoundException cnfe ) {
Illustrate ill = System.err.println( "I could not find a class named \"" +
(Illustrate)theClass.getAnnotation( Illustrate.class ); cnfe.getMessage() + "\"." );
System.err.println( "Are you sure about that name?" );
}
}
… continued … }

Advanced programming in Java Advanced programming in Java

(c) Marek Běhálek, Katedra informatiky FEI VŠB-TU Ostrava 21


Advanced programming in Java

Annotations – Compilation and


Execution Annotations – Execution
$ javac *.java
Note: Suggester.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details. $ java Suggester
In what class are you interested? Coin
$ java Suggester That class will teach you nothing.
In what class are you interested? Suggester
Look at this class if you'd like to see examples of $ java Suggester
the enumeration feature In what class are you interested? Foo
the forLoop feature I could not find a class named "Foo".
Are you sure about that name?
$ 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

Advanced programming in Java Advanced programming in Java

Annotations – Example – JPA Annotations – Example – JUnit


Annotations Annotations
• When using JPA, you can configure the JPA • Annotations and support for Java 5 are key
behavior of your entities using annotations: new features of JUnit 4:
• @Entity - designate a plain old Java object (POJO) • @Test – annotates test method
class as an entity so that you can use it with JPA
services • @Before, @After– annotates setUp() and
• @Table, @Column, @JoinColumn, tearDown() methods for each test
@PrimaryKeyJoinColumn – database schema attributes
• @BeforeClass, @AfterClass – class-scoped
• @OneToOne, @ManyToMany – relationship mappings setUp() and tearDown()
• @Inheritance, @DiscriminatorColumn – inheritance
controlling • @Ignore – do not run test

Advanced programming in Java Advanced programming in Java

(c) Marek Běhálek, Katedra informatiky FEI VŠB-TU Ostrava 22


Advanced programming in Java

Java I/O – Reading & Writing Java I/O – Reading & Writing
Data Data
 Data can come from many Sources & go to Reading

many Destinations Open a Stream


While more
 Memory Information
 Disk Read

 Network Close the Stream

 Whatever the Source or Destination, a Writing


Open a Stream
Stream has to be opened to Read/Write While more Information
Data Write
Close the Stream

Advanced programming in Java Advanced programming in Java

Java I/O – Reading & Writing


Data Java I/O – Character Streams
 java.io Package includes these Stream  Reader and
Classes Writer are
 Character Streams are used for 16-bit Characters abstract
super classes
– Uses Reader & Writer Classes for character
 Byte Streams are used for 8-bit Bytes – Uses streams (16-
InputStream & OutputStream Classes Used for bit data)
Image, Sound Data etc.  Sub classes
provide
specialized
behavior

Advanced programming in Java Advanced programming in Java

(c) Marek Běhálek, Katedra informatiky FEI VŠB-TU Ostrava 23


Advanced programming in Java

Java I/O – Byte Streams Java I/O – I/O Super Classes (1)
 Reader and InputStream define similar APIs but
 InputStream
and for different data types
OutoutStream
are abstract int read()
super classes int read(char cbuf[]) Reader
for byte int read(char cbuf[], int offset, int length)
streams (8-bit
data)
int read()
 Sub classes
provide int read(byte cbuf[]) InputStream
specialized int read(byte cbuf[], int offset, int length)
behavior

Advanced programming in Java Advanced programming in Java

Java I/O – I/O Super Classes (2) Type of I/O Streams Description

CharArrayReader
Use these streams to read from and write to memory.

Writer and OutputStream define similar APIs but


CharArrayWriter
You create these streams on an existing array and then
 ByteArrayInputStream
use the read and write methods to read from or write to the array.
ByteArrayOutputStream
for different data types Memory Use StringReader to read characters from a String in memory.
StringReader Use StringWriter to write to a String. StringWriter collects the characters
StringWriter written to it in a StringBuffer, which can then be converted to a String.
StringBufferInputStream StringBufferInputStream is similar to StringReader, except that it reads bytes
int write() from a StringBuffer.
int write(char cbuf[]) Writer PipedReader
Implement the input and output components of a pipe. Pipes are used to
PipedWriter
int write(char cbuf[], int offset, int length) Pipe
PipedInputStream
channel the output from one thread into the input of another.
PipedOutputStream

FileReader Collectively called file streams, these streams are used to read from or write
int write() FileWriter to a file on the native file system.
File
FileInputStream
int write(byte cbuf[]) OutputStream FileOutputStream
int write(byte cbuf[], int offset, int length)
Object N/A
Serializati- ObjectInputStream Used to serialize objects.
on ObjectOutputStream

Advanced programming in Java Advanced programming in Java

(c) Marek Běhálek, Katedra informatiky FEI VŠB-TU Ostrava 24


Advanced programming in Java

Java I/O – Stream wrapping Java I/O – Decorator Pattern

 BufferedReader class can be used for efficient reading  Capabilities are added using a design called
of characters, arrays and lines the Decorator Pattern.
BufferedReader in = new BufferedReader(new FileReader("foo.in")); Component 1

 BufferedWriter and PrintWriter classes can be used for +operation() -component

efficient writing of characters, arrays and lines and


other data types ConcreteComponent
-
Decorator

+operation() +operation() 1

BufferedWriter out = new BufferedWriter(newFileWriter("foo.out"));


component.operation()

PrintWriter out= new PrintWriter(new BufferedWriter(new FileWriter("foo.out"))); ConcreteDecorator1 ConcreteDecorator2

+operation() +operation()
+addedOperation1() +addedOperation2()

super.operation()
addedOperation2()

Advanced programming in Java Advanced programming in Java

Java I/O – Purpose of Decorator Java I/O – Java decorators


 Best way to think of this is as follows:  All Java i/o decorator classes inherit from FilterInputStream and
 There are two important issues when constructing FilterOutputStream
 Look at the api for these classes and note a few things:
an i/o library  They wrap instances of InputStream/OutputStream respectively.
 Where the i/o is going (file, etc).  They inherit from InputStream/OutputStream respectively
 How the data is represented (String, native type, etc.)  This is an odd inheritence hierarchy but is necessary to ensure that
the FilterStreams support the same interface as the underlying
 Rather than create a class for each combination, class.
Decorator classes allow you to mix and match,
augment functionality of base classes. public class FilterInputStream extends InputStream {
 This is a bit confusing but is very flexible. protected InputStream in;
 Decorators can also add other capabilities, such as protected FilterInputStream(InputStream in) {
peek ahead, push back, write line number, etc. this.in = in;

}}

Advanced programming in Java Advanced programming in Java

(c) Marek Běhálek, Katedra informatiky FEI VŠB-TU Ostrava 25


Advanced programming in Java

Java I/O – File Handling - Java I/O – Getting User Input in


Character Streams Command Line
import java.io.*;
public class CopyCharacters {  Read as reading from the standard input
public static void main(String[] args) throws IOException { device which is treated as an input stream
File inputFile = new File(“InputFile.txt");
File outputFile = new File(“OutputFile.txt");
Create File Objects represented by System.in
FileReader in = new FileReader(inputFile); BufferedReader input= new
Create File Streams
FileWriter out = new FileWriter(outputFile); BufferedReader(newInputStreamReader(System.in));
int c;
System.out.println("Enter the name :" );
while ((c = in.read() ) != -1) // Read from Stream String name =input.readLine();
out.write(c); // Write to Stream
in.close();
out.close(); Close the Streams  Throws java.io.IOException
}
}
Advanced programming in Java Advanced programming in Java

Java I/O – Object Serialization Java I/O – Object Serialization


 To allow to Read & Write Objects  Object Serialization is used in
 Remote Method Invocation (RMI) : communication
between objects via sockets
 The State of the Object is represented in a  Lightweight persistence : the archival of an object
Serialized form sufficient to reconstruct it for use in a later invocation of the same program
later  An Object of any Class that implements the Serializable
Interface can be serialized
 Streams to be used  public class MyClass implements Serializable {
...
 ObjectInputStream }
 ObjectOutputStream  Serializable is an Empty Interface, no methods have to be
implemented

Advanced programming in Java Advanced programming in Java

(c) Marek Běhálek, Katedra informatiky FEI VŠB-TU Ostrava 26


Advanced programming in Java

Java I/O – Object Serialization


Example Java I/O – Object Serialization
 Writing to an ObjectOutputStream  Reading from an ObjectInputStream

FileOutputStream fos = new FileOutputStream("t.tmp"); FileInputStream in = new FileInputStream("Time");


ObjectOutputStream oos = new ObjectOutputStream(fos); ObjectInputStream s = new ObjectInputStream(in);
oos.writeInt(12345); String today = (String)s.readObject();
oos.writeObject("Today");
Date date = (Date)s.readObject();
oos.writeObject(new Date());
oos.close();
 The objects must be read from the stream in
 ObjectOutputStream must be constructed on the same order in which they were written
another Stream
Advanced programming in Java Advanced programming in Java

Java I/O – Protecting sensitive


Java I/O – Object Serialization data
Problem: During deserialization, the private state of the object is
 Specialized behavior can be provided in restored, to avoid compromising a class, you must provide either
that –
serilazation and deserialization by  the sensitive state of an object must not be restored from the stream
implementing the following methods 
or
that it must be reverified by the class.
Solution
private void writeObject(java.io.ObjectOutputStream out) throws  mark fields that contain sensitive data as private transient. transient
and static fields are not serialized or deserialized
IOException  Particularly sensitive classes should not be serialized. To accomplish
this, the object should not implement either the Serializable or
Externalizable interface.
private void readObject(java.io.ObjectInputStream in) throws  Some classes may find it beneficial to allow writing and reading but to
IOException, ClassNotFoundException; specifically handle and revalidate the state as it is deserialized. The
class should implement writeObject and readObject methods to save
and restore only the appropriate state.

Advanced programming in Java Advanced programming in Java

(c) Marek Běhálek, Katedra informatiky FEI VŠB-TU Ostrava 27


Advanced programming in Java

Java I/O – Example: Creating


Java I/O – Compression in Java ZIP file (1)
String[] filenames = new String[]{"filename1", "filename2"};
 java.util.jar byte[] buf = new byte[1024];

 JarInputStream, JarOutputStream try {


String outFilename = "outfile.zip";
ZipOutputStream out = new ZipOutputStream(
new FileOutputStream(outFilename));
 java.util.zip
for (int i=0; i<filenames.length; i++) {
 ZIPInputStream, ZIPOuputStream FileInputStream in = new FileInputStream(filenames[i]);

 GZIPInputStream, GZIPOutputStream // <komprese souboru>

in.close();
}
out.close();
} catch (IOException e) {}

Advanced programming in Java Advanced programming in Java

Java I/O – Example: Creating ZIP


file (2) Java I/O – Example: Using ZIP file
// <komprese souboru> try {
ZipFile zf = new ZipFile(zipFileName);
// Vytvoření nové výstupní položky
out.putNextEntry(new ZipEntry(filenames[i])); for (Enumeration entries = zf.entries();
entries.hasMoreElements();) {
// Přenos obsahu souboru
int len; String zipEntryName =
while ((len = in.read(buf)) > 0) { ((ZipEntry)entries.nextElement()).getName();
out.write(buf, 0, len);
} System.out.println("Entry : " + zipEntryName );
}
// Uzavření výstupní položky } catch (IOException e) {
out.closeEntry(); e.printStackTrace();
}
Advanced programming in Java Advanced programming in Java

(c) Marek Běhálek, Katedra informatiky FEI VŠB-TU Ostrava 28


Advanced programming in Java

Java I/O – Example: Extracting ZIP


file Threads – Basics
ZipEntry zipEntry = (ZipEntry)entries.nextElement();  Process (task)
String zipEntryName = zipEntry.getName(); int lastDirSep;
 Separate “program” with his own memory (address space)
if ( (lastDirSep = zipEntryName.lastIndexOf('/')) > 0 ) {
String dirName = zipEntryName.substring(0, lastDirSep);  Based on operating system
(new File(dirName)).mkdirs();  Operating system is responsible for process execution.
}  Multitasking – operation system ability to perform
if (!zipEntryName.endsWith("/")) { several processes at the same time.
OutputStream out = new FileOutputStream(zipEntryName);  Thread
InputStream in = zf.getInputStream(zipEntry);
byte[] buf = new byte[1024]; int len;  „light waited process“
while((len = in.read(buf)) > 0) out.write(buf, 0, len);  One process may be composed from several threads.
out.close(); in.close();  Thread‟s creation is much faster.
}

Advanced programming in Java Advanced programming in Java

Threads – Execution of multi-


Threads – Level of parallelism thread applications(1)
Code-Granularity
Code Item
Sockets/ Task i-l Task i Task i+1 Large grain
PVM/MPI (task level) CPU
P1
Program

P2 CPU
func1 ( ) func2 ( ) func3 ( )
{ { { Medium grain
Threads .... .... .... (control level) P3 CPU
.... .... ....
} } } Function (thread)

Fine grain time


a ( 0 ) =.. a ( 1 )=.. a ( 2 )=.. (data level)
Compilers b ( 0 ) =.. b ( 1 )=.. b ( 2 )=..
Loop (Compiler)
amount of running threads <= amount of CPUs
Very fine grain
CPU + x Load (multiple issue)
Advanced programming in Java Advanced programming in Java
With hardware

(c) Marek Běhálek, Katedra informatiky FEI VŠB-TU Ostrava 29


Advanced programming in Java

Threads – Execution of multi- Threads – Creating concurrent


thread applications (2) applications(1)
 Concurrent thread execution  We can use threads in Java.
 Threads are executed by Java Virtual
P1 Machine.
P2 CPU  They are executed in parallel if possible.
P3

time

amount of running threads > amount of CPUs


Advanced programming in Java Advanced programming in Java

Threads – Creating concurrent


applications(2) Threads – Thread Creation
 Thread properties in Java  Every class can be a starting point of a new
 Thread execution starts at specific point of program
(main method). thread. It must:
 Instructions are executed one by one with respect to  Implement interface java.lang.Runnable;
source code.
 Threads can cooperate together, but they are executed  Or extends class java.lang.Thread.
separately.
 Every thread can access programs data (with respect to  Start up point is the run() method in both
Java security rules). cases.
 Local properties – are accessible within a method only.
 Instance and static properties – are shared between
threads.

Advanced programming in Java Advanced programming in Java

(c) Marek Běhálek, Katedra informatiky FEI VŠB-TU Ostrava 30


Advanced programming in Java

Threads – Extension of class


Thread Threads – Example
 Your class must extend class Thread and re-implement method class MyThread extends Thread { // thread
run(). public void run() {
class MyThread extends Thread
{ System.out.println(" this thread is running ... ");
public void run() }
{ } // end class MyThread
// thread body
}
} class ThreadEx1 { // using thread
 Thread‟s creation: public static void main(String [] args ) {
MyThread thr = new MyThread();
MyThread t = new MyThread();
 Running created thread:
//methods start predefined method run
thr.start();
t.start();
}
}

Advanced programming in Java Advanced programming in Java

Threads – Runnable interface Threads – Example


class MyThread implements Runnable class MyThread implements Runnable {
{ public void run() {
..... System.out.println(" this thread is running ... ");
public void run() }
{
}
// tělo vlákna
} class ThreadEx2 {
} public static void main(String [] args ) {
 Thread‟s creation:
MyThread myObject = new MyThread(); Thread t = new Thread(new MyThread());
Thread thr1 = new Thread( myObject );
t.start();
 Thread‟s execution: }
thr1.start(); }

Advanced programming in Java Advanced programming in Java

(c) Marek Běhálek, Katedra informatiky FEI VŠB-TU Ostrava 31


Advanced programming in Java

Threads – Thread class Threads – Starting threads


 Basic properties:  Invoking its start method causes an instance
of class Thread to initiate its run method
 Constructors
 public Thread()
 A Thread terminates when its run method
 public Thread(Runnable target)
completes by either returning normally or
throwing an unchecked exception
 public Thread(String name)
 public Thread(Runnable target, String name)
 Threads are not restartable, even after they
terminate
 Basic methods
 isAlive returns true if a thread has been
 public void start()
started by has not terminated
 public void run()

Advanced programming in Java Advanced programming in Java

Threads – More Thread


methods Threads – Priorities
 Thread.currentThread returns a  Each Thread has a priority, between
Thread.MIN_PRIORITY and
reference to the current Thread Thread.MAX_PRIORITY (from 1 to 10)
 Thread.sleep(long msecs) causes the  Each new thread has the same priority as the thread
that created it
current thread to suspend for at least  The initial thread associated with a main by default
msecs milliseconds has priority Thread.NORM_PRIORITY (5)
 Thread.interrupt is the preferred  getPriority gets current Thread priority,
setPriority sets priority
method for stopping a thread (not  A scheduler is generally biased to prefer running
Thread.stop) threads with higher priorities (depends on JVM
implementation)

Advanced programming in Java Advanced programming in Java

(c) Marek Běhálek, Katedra informatiky FEI VŠB-TU Ostrava 32


Advanced programming in Java

Threads – The “run queue” of Threads – Thread States and


runnable threads Scheduling
 The Java language specification does not specify  A Java thread can be in new, runnable,
how Java is supposed to choose the thread to
run if there are several runnable threads of running, suspended, blocked, suspended-
equal priority. blocked and dead.
 One possibility – pick a thread and run it until it  The Threads class has methods that move
completes, or until it executes a method that
causes it to move into a non-running state. the thread from one state to another.
 Another possibility – “time slicing”: pick a
thread and run it for a short period of time.
Then, if it is not finished, suspend it and pick
another thread to run for the same period of
time.

Advanced programming in Java Advanced programming in Java

Threads – Thread/process
states Threads – Thread states (1)
start yield
 New state – a Thread newly created.
 Runnable – after being started, the Thread can
stop sleep/suspend resume be run. It is put into the “run queue” of
0 1 2 3 4 Threads and waits its turn to run. “Runnable”
run
stop/end suspend does not mean “running”.
dispatch
stop  Running – the thread is executing its code. On
stop a uniprocessor machine, at most one thread can
run at a time.
1 – terminated 3 – suspended
2 – running 4 - runnable
Advanced programming in Java Advanced programming in Java

(c) Marek Běhálek, Katedra informatiky FEI VŠB-TU Ostrava 33


Advanced programming in Java

Threads – Thread states (2) Threads – Thread states (3)


 Blocked – the thread is waiting for something to  Dead
happen  The final state. After reaching this state the
It is waiting for an i/o operation it is executing Thread can no longer execute.
to complete  A thread can reach this state after the run
It has been told to sleep for a specified period method is finished, or by something executing its
of time through the sleep method stop() method.
It has executed the wait() method and will  Threads can kill themselves, or a thread can kill
block until another thread executes a notify() another thread.
or notifyAll() method.
 It will return to runnable state after sleeping,
notifying, etc.
Advanced programming in Java Advanced programming in Java

Threads – Thread’s life cycle


conclusion Threads – join( ) Method
Basic Thread‟s states: Initial, Runnable, Not Runnable a Dead.

 A call to t1.join( ) causes the current thread
 Thread‟s methods that affects his life cycle.
 public void start() to block until Thread t1 terminates
 public void run()
 Throws InterruptedException
 public static void sleep(long milisekund)
 public boolean isAlive()  main( ) can join on all threads it spawns to
 public void join()
wait for them all to finish
 public void interrupt()
 public boolean isInterrupted()  Optional timeout parameter (milliseconds):
 public static void yield()
 t1.join( 2000 );
 public Thread.state getState()

Advanced programming in Java Advanced programming in Java

(c) Marek Běhálek, Katedra informatiky FEI VŠB-TU Ostrava 34


Advanced programming in Java

Threads – Daemon Threads Threads – Concurrency


 by themselves do not keep a VM alive  An object in a program can be changed by more
than one thread
 call setDaemon(true)  Q: Is the order of changes that were preformed on
 call must occur before calling start( ); otherwise, the object important? Can it be performed at the
an IllegalThreadStateException is thrown same time?
 Thread‟s default daemon status is the same  A race condition – the outcome of a program is
affected by the order in which the program's
as the thread that spawned it threads are allocated CPU time
 Call isDaemon( ) to see if thread is a  Two threads are simultaneously modifying a single
daemon object
 Both threads “race” to store their value
Advanced programming in Java Advanced programming in Java

Threads – Critical Section Threads – Example


public class BankAccount {
 Section of program that must be executed
exclusively by one thread only. private float balance;
 Java allows mutual exclusion on objects
 Acquires the object's lock. (Another way of saying public synchronized void deposit(float amount) {
“completing the preprotocol”.) balance += amount;
 synchronized(obj) { code; } means that }
no other synchronized(obj) block can be
executed simultaneously with code. public synchronized void withdraw(float amount) {
 Java use Monitors for locking objects. balance -= amount;
}
}
Advanced programming in Java Advanced programming in Java

(c) Marek Běhálek, Katedra informatiky FEI VŠB-TU Ostrava 35


Advanced programming in Java

Threads – Monitors (1) Threads – Monitor (2)


 Each object has a “monitor” that is a token  Entering a monitor is also referred to as
used to determine which application thread has
locking the monitor, or acquiring ownership
control of a particular object instance
of the monitor
 In execution of a synchronized method (or
block), access to the object monitor must be  If a thread A tries to acquire ownership of a
gained before the execution monitor and a different thread has already
 Access to the object monitor is queued entered the monitor, the current thread (A)
must wait until the other thread leaves the
monitor
Advanced programming in Java Advanced programming in Java

Threads – Java Locks are


Reentrant Threads – The wait() Method (1)
 Is there a problem with the following code?  The wait() method is part of the
java.lang.Object interface
 It requires a lock on the object‟s monitor to
public class Test {
public synchronized void a() {
execute
b();  It must be called from a synchronized
System.out.println(“I am at a”);
}
method, or from a synchronized segment of
public synchronized void b() { code. Why?
System.out.println(“I am at b”);
}
}
Advanced programming in Java Advanced programming in Java

(c) Marek Běhálek, Katedra informatiky FEI VŠB-TU Ostrava 36


Advanced programming in Java

Threads – The wait() Method (2) Threads – The wait() Method (3)

 wait() causes the current thread to wait  wait() is also similar to yield()
until another thread invokes the notify()  Both take the current thread off the execution
method or the notifyAll() method for this stack and force it to be rescheduled
object  However, wait() is not automatically put
 Upon call for wait(), the thread releases back into the scheduler queue
ownership of this monitor and waits until  notify() must be called in order to get a thread
another thread notifies the waiting threads back into the scheduler‟s queue

of the object
Advanced programming in Java Advanced programming in Java

Threads – Wait and Notify: Code Threads – Wait/Notify Sequence


 Consumer:
synchronized (lock) {
while (!resourceAvailable()) { Lock Object
1. synchronized(lock){ 3. produceResource()
lock.wait(); 4. synchronized(lock) {
2. lock.wait();
} 5. lock.notify();
9. consumeResource();
consumeResource(); 10. } 6.}
} 7. Reacquire lock
8. Return from wait()
 Producer:
produceResource(); Consumer Producer
synchronized (lock) { Thread Thread
lock.notifyAll();
}

Advanced programming in Java Advanced programming in Java

(c) Marek Běhálek, Katedra informatiky FEI VŠB-TU Ostrava 37


Advanced programming in Java

Threads – Wait/Notify Sequence Threads – Wait/Notify Sequence

Lock Object Lock Object


1. synchronized(lock){ 3. produceResource() 1. synchronized(lock){ 3. produceResource()
2. lock.wait(); 4. synchronized(lock) { 2. lock.wait(); 4. synchronized(lock) {
5. lock.notify(); 5. lock.notify();
9. consumeResource(); 9. consumeResource();
10. } 6.} 10. } 6.}
7. Reacquire lock 7. Reacquire lock
8. Return from wait() 8. Return from wait()
Consumer Producer Consumer Producer
Thread Thread Thread Thread

Advanced programming in Java Advanced programming in Java

Threads – Wait/Notify Sequence Threads – Wait/Notify Sequence

Lock Object Lock Object


1. synchronized(lock){ 3. produceResource() 1. synchronized(lock){ 3. produceResource()
2. lock.wait(); 4. synchronized(lock) { 2. lock.wait(); 4. synchronized(lock) {
5. lock.notify(); 5. lock.notify();
9. consumeResource(); 9. consumeResource();
10. } 6.} 10. } 6.}
7. Reacquire lock 7. Reacquire lock
8. Return from wait() 8. Return from wait()
Consumer Producer Consumer Producer
Thread Thread Thread Thread

Advanced programming in Java Advanced programming in Java

(c) Marek Běhálek, Katedra informatiky FEI VŠB-TU Ostrava 38


Advanced programming in Java

Threads – Wait/Notify Sequence Threads – Wait/Notify Sequence

Lock Object Lock Object


1. synchronized(lock){ 3. produceResource() 1. synchronized(lock){ 3. produceResource()
2. lock.wait(); 4. synchronized(lock) { 2. lock.wait(); 4. synchronized(lock) {
5. lock.notify(); 5. lock.notify();
9. consumeResource(); 9. consumeResource();
10. } 6.} 10. } 6.}
7. Reacquire lock 7. Reacquire lock
8. Return from wait() 8. Return from wait()
Consumer Producer Consumer Producer
Thread Thread Thread Thread

Advanced programming in Java Advanced programming in Java

Threads – Wait/Notify Sequence Threads – Wait/Notify Sequence

Lock Object Lock Object


1. synchronized(lock){ 3. produceResource() 1. synchronized(lock){ 3. produceResource()
2. lock.wait(); 4. synchronized(lock) { 2. lock.wait(); 4. synchronized(lock) {
5. lock.notify(); 5. lock.notify();
9. consumeResource(); 9. consumeResource();
10. } 6.} 10. } 6.}
7. Reacquire lock 7. Reacquire lock
8. Return from wait() 8. Return from wait()
Consumer Producer Consumer Producer
Thread Thread Thread Thread

Advanced programming in Java Advanced programming in Java

(c) Marek Běhálek, Katedra informatiky FEI VŠB-TU Ostrava 39


Advanced programming in Java

Threads – Wait/Notify Sequence Threads – Wait/Notify Sequence

Lock Object Lock Object


1. synchronized(lock){ 3. produceResource() 1. synchronized(lock){ 3. produceResource()
2. lock.wait(); 4. synchronized(lock) { 2. lock.wait(); 4. synchronized(lock) {
5. lock.notify(); 5. lock.notify();
9. consumeResource(); 9. consumeResource();
10. } 6.} 10. } 6.}
7. Reacquire lock 7. Reacquire lock
8. Return from wait() 8. Return from wait()
Consumer Producer Consumer Producer
Thread Thread Thread Thread

Advanced programming in Java Advanced programming in Java

Threads – Example - Producer Threads – Example - Customer


class Producer extends Thread{ class Customer extends Thread{
private Pool pool;
private Pool pool;
public Producer(Pool pool) { private String name;
this.pool=pool; public Customer(Pool pool,String name) {
} this.pool=pool;
public void run() {
this.name=name;
for(int i=0;i<10;i++) { }
System.out.println("Produced item: "+i); public void run() {
pool.putItem(i); for(int i=0;i<5;i++) {
try{
Thread.sleep(new java.util.Random().nextInt(1000));
int tmp=pool.getItem();
}catch (InterruptedException e) {} System.out.println(
} name+": Consumed item: "+tmp);
} }
}
}
}
Advanced programming in Java Advanced programming in Java

(c) Marek Běhálek, Katedra informatiky FEI VŠB-TU Ostrava 40


Advanced programming in Java

Threads – Example - Pool Threads – Example - Pool


class Pool { public synchronized int getItem() {
private int item; while(!full) {
private boolean full = false;
try{
public synchronized void putItem(int item) { wait();
while(full) { }catch(InterruptedException e) {}
try{ }
wait();
int tmp= this.item;
}catch(InterruptedException e){ }
} this.full=false;
this.item=item; notifyAll();
full=true; return tmp;
notifyAll(); }
}
}

Advanced programming in Java Advanced programming in Java

Threads – Example - main Threads – Example - output


Produced item: 0
public static void main(String[] args) { A: Consumed item: 0
Produced item: 1
Pool pool = new Pool(); B: Consumed item:
Produced item: 2
1

A: Consumed item: 2
Producer producer=new Producer(pool); Produced item: 3
B: Consumed item: 3
Customer consumer1=new Customer(pool,"A"); Produced item: 4
A: Consumed item: 4
Customer consumer2=new Customer(pool,"B"); Produced item: 5
A: Consumed item: 5
Produced item: 6
consumer1.start(); B: Consumed item: 6
Produced item: 7
consumer2.start(); A: Consumed item:
Produced item: 8
7

B: Consumed item: 8
producer.start(); Produced item: 9
B: Consumed item: 9
}
Advanced programming in Java Advanced programming in Java

(c) Marek Běhálek, Katedra informatiky FEI VŠB-TU Ostrava 41


Advanced programming in Java

Threads – Locks and Pre-Java 5 Threads –“New” Java


Approach Concurrency Library
 Each instance of the Java Object class has an  What was just shown is not good design (some
object-lock argue it‟s truly broken)
 Use the synchronized keyword for a method  In Java 5, new approach and library support
 Or block of code
 More like C#, by the way
 When entering that method, that thread owns the
lock  java.util.concurrent
 When leaving that method, lock is released  Lock objects (an interface)
 Condition: something that allows coordination  Lock has lock() and unlock() methods
 wait() – sleep until the condition for that object  Conditions objects (more than one)
becomes true
 Available from a Lock object
 notifyAll() – tell other threads the condition is true
 Condition has signalAll() and await() methods
Advanced programming in Java Advanced programming in Java

Threads – Using Java 5 Lock


and Conditions
 Define objects in Queue class:
private Lock queueLock = new ReentrantLock();
private Condition spaceAvailable =
queueLock.newCondition();
 Need to check a condition?
while ( unable to proceed )
spaceAvailable.await();
// now proceed
 Some place else:
spaceAvailable.signalAll();
Advanced programming in Java

(c) Marek Běhálek, Katedra informatiky FEI VŠB-TU Ostrava 42

You might also like