Basic Java Part 3

35
7/28/2019 Basic Java Part 3 http://slidepdf.com/reader/full/basic-java-part-3 1/35  Basic Java Part 3

Transcript of Basic Java Part 3

Page 1: Basic Java Part 3

7/28/2019 Basic Java Part 3

http://slidepdf.com/reader/full/basic-java-part-3 1/35

 Basic Java Part 3

Page 2: Basic Java Part 3

7/28/2019 Basic Java Part 3

http://slidepdf.com/reader/full/basic-java-part-3 2/35

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited

2

Agenda

• Basic I/O

• Concurrency

Page 3: Basic Java Part 3

7/28/2019 Basic Java Part 3

http://slidepdf.com/reader/full/basic-java-part-3 3/35

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited

3

Basic I/O

•  I/O Streams

 – An I/O stream represents an input source or an output destination.

 – A stream can represent many different kinds of sources and destinations, including disk files,devices, other programs, and memory arrays.

 – Streams support many different kinds of data, including simple bytes, primitive data types,localized characters, and objects.

• A stream is a sequence of data

• Reading information into a program 

Page 4: Basic Java Part 3

7/28/2019 Basic Java Part 3

http://slidepdf.com/reader/full/basic-java-part-3 4/35

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited

4

Basic I/O

• Writing information from a program

• Byte StreamsPrograms use byte streams to perform input and output of 8-bit bytes. All byte stream classesare descended from InputStream and OutputStream.

• Example Program using FileInputStream and FileOutputStreamCreate text file (xanadu.txt) for read write operation with the following content:

In Xanadu did Kubla Khan A stately pleasure-dome decree: Where Alph, the sacred river, ranThrough caverns measureless to man Down to a sunless sea.

Page 5: Basic Java Part 3

7/28/2019 Basic Java Part 3

http://slidepdf.com/reader/full/basic-java-part-3 5/35

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited

5

Basic I/O

Always Close Streams: Closing a stream when it's no longer needed is very important soimportant that CopyBytes uses a finally block to guarantee that both streams will be closed evenif an error occurs. This practice helps avoid resource leaks.

Page 6: Basic Java Part 3

7/28/2019 Basic Java Part 3

http://slidepdf.com/reader/full/basic-java-part-3 6/35

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited

6

Basic I/O

• When Not to Use Byte Streams

 – CopyBytes seems like a normal program, but it actually represents a kind of low-level I/Othat you should avoid.

 – Since xanadu.txt contains character data, the best approach is to use character streams.

 – There are also streams for more complicated data types.

 – Byte streams should only be used for the most primitive I/O.

• Character Streams

 – The Java platform stores character values using Unicode conventions.

 – Character stream I/O automatically translates this internal format to and from the localcharacter set.

 – In Western locales, the local character set is usually an 8-bit superset of ASCII.

Page 7: Basic Java Part 3

7/28/2019 Basic Java Part 3

http://slidepdf.com/reader/full/basic-java-part-3 7/35

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited

7

Basic I/O

• In CopyCharacters, the int variable holds a character value in its last 16 bits; in CopyBytes, the

int variable holds a byte value in its last 8 bits.

Page 8: Basic Java Part 3

7/28/2019 Basic Java Part 3

http://slidepdf.com/reader/full/basic-java-part-3 8/35Any use, copying or distribution without written permission from UnitedHealth Group is prohibited

8

Basic I/O

• Line-Oriented I/O

A line terminator can be acarriage-return/line-feed sequence("\r\n"), a single carriage-return("\r"), or a single line-feed ("\n").Supporting all possible lineterminators allows programs toread text files created on anyof the widely used operating systems.

Page 9: Basic Java Part 3

7/28/2019 Basic Java Part 3

http://slidepdf.com/reader/full/basic-java-part-3 9/35Any use, copying or distribution without written permission from UnitedHealth Group is prohibited

9

Basic I/O

• Buffered Streams

Unbuffered I/O: This means that each read or write request is handled directly by theunderlying OS. This can make a program much less efficient, since each such request oftentriggers disk access, network activity, or some other operation that is relatively expensive.

Solution :To reduce this kind of overhead, the Java platform implements buffered I/O streams. Bufferedinput streams read data from a memory area known as a buffer; the native input API is calledonly when the buffer is empty. Similarly, buffered output streams write data to a buffer, and thenative output API is called only when the buffer is full

A program can convert an unbuffered stream into a buffered streamExample:

• Flushing Buffered Streams It often makes sense to write out a buffer at critical points, without waiting for it to fill. This isknown as flushing the buffer

Page 10: Basic Java Part 3

7/28/2019 Basic Java Part 3

http://slidepdf.com/reader/full/basic-java-part-3 10/35Any use, copying or distribution without written permission from UnitedHealth Group is prohibited

10

Basic I/O

• Scanning and Formatting

The scanner API breaks input into individual tokens associated with bits of data. Theformatting API assembles data into nicely formatted, human-readable form

• Breaking Input into TokensBy default, a scanner uses white space to separate tokens. (White space characters includeblanks, tabs, and line terminators

Example

Page 11: Basic Java Part 3

7/28/2019 Basic Java Part 3

http://slidepdf.com/reader/full/basic-java-part-3 11/35Any use, copying or distribution without written permission from UnitedHealth Group is prohibited

11

Basic I/O

• The format Method

The format method formats multiple arguments based on a format string. The format stringconsists of static text embedded with format specifiers; except for the format specifiers, theformat string is output unchanged.

• Example

The three conversions used here are:

• d formats an integer value as a decimal value.• f formats a floating point value as a decimal value.• n outputs a platform-specific line terminator

Page 12: Basic Java Part 3

7/28/2019 Basic Java Part 3

http://slidepdf.com/reader/full/basic-java-part-3 12/35Any use, copying or distribution without written permission from UnitedHealth Group is prohibited

12

Basic I/O

• I/O from the Command Line

 – Standard StreamsStandard Streams are a feature of many operating systems. By default, they read inputfrom the keyboard and write output to the display

 – The Java platform supports three Standard Streams: Standard Input, accessed through

System.in; Standard Output, accessed through System.out; and Standard Error,

accessed through System.err.

 – To use Standard Input as a character stream, wrap System.in in InputStreamReader:

as follows:InputStreamReader cin = new InputStreamReader(System.in);

 – The Console

 – A more advanced alternative to the Standard Streams is the Console

 – The Console is particularly useful for secure password entry

 – The Console object also provides input and output streams that are true character

streams, through its reader and writer methods. – Before a program can use the Console, it must attempt to retrieve the Console object

by invoking System.console().

Page 13: Basic Java Part 3

7/28/2019 Basic Java Part 3

http://slidepdf.com/reader/full/basic-java-part-3 13/35Any use, copying or distribution without written permission from UnitedHealth Group is prohibited

13

Basic I/O

• Exercise

1. Attempt to retrieve the Console object. If the object is not available, abort.

2. Invoke Console.readLine to prompt for and read the user's login name.

3. Invoke Console.readPassword to prompt for and read the user's existingpassword.

4. Invoke verify to confirm that the user is authorized to change the password. (Inthis example, verify is a dummy method that always returns true.)

5. Repeat the following steps until the user enters the same password twice:

 – Invoke Console.readPassword twice to prompt for and read a new password.

 – If the user entered the same password both times, invoke change to change it. (Again,

change is a dummy method.)

 – Overwrite both passwords with blanks.

6. Overwrite the old password with blanks.

Page 14: Basic Java Part 3

7/28/2019 Basic Java Part 3

http://slidepdf.com/reader/full/basic-java-part-3 14/35Any use, copying or distribution without written permission from UnitedHealth Group is prohibited

14

Basic I/O

• Data StreamsData streams support binary I/O of primitive data type values (boolean, char, byte, short, int,long, float, and double) as well as String values.

• Fields in Data Stream example

Page 15: Basic Java Part 3

7/28/2019 Basic Java Part 3

http://slidepdf.com/reader/full/basic-java-part-3 15/35Any use, copying or distribution without written permission from UnitedHealth Group is prohibited

15

Basic I/O

• File I/O

 – File is a class that helps you write platform-independent code that examines andmanipulates files and directories.

 – Random access files support non-sequential access to disk file data.

• Creating a File ObjectFile a = new File("xanadu.txt");

• File Method Examples

Page 16: Basic Java Part 3

7/28/2019 Basic Java Part 3

http://slidepdf.com/reader/full/basic-java-part-3 16/35Any use, copying or distribution without written permission from UnitedHealth Group is prohibited

16

Basic I/O

• Another example for creating a File Object

• More File Method Examples 

Look into the Notes section for example on File Stuff

Page 17: Basic Java Part 3

7/28/2019 Basic Java Part 3

http://slidepdf.com/reader/full/basic-java-part-3 17/35Any use, copying or distribution without written permission from UnitedHealth Group is prohibited

17

Basic I/O

• Random Access FilesRandom access files permit nonsequential, or random, access to a file's contents

• Suppose that you want to extract a specific file from a ZIP archive. If you use a sequentialaccess stream, you have to:1. Open the ZIP archive.2. Search through the ZIP archive until you locate the file you want to extract.3. Extract the file.4. Close the ZIP archive

• You can extract the same file from the ZIP archive more efficiently by using the seek feature of

a random access file and following these steps:1. Open the ZIP archive.2. Seek to the directory entry and locate the entry for the file you want to extract from the ZIParchive.3. Seek (backward) within the ZIP archive to the position of the file to extract.4. Extract the file.5. Close the ZIP archive.

Page 18: Basic Java Part 3

7/28/2019 Basic Java Part 3

http://slidepdf.com/reader/full/basic-java-part-3 18/35Any use, copying or distribution without written permission from UnitedHealth Group is prohibited

18

• Exercise

Implement a pair of classes, one Reader and one Writer, that count the number of timesa particular character, such as e, is read or written. The character can be specifiedwhen the stream is created. Write a program to test your classes. You can usexanadu.txt as the input file.

Page 19: Basic Java Part 3

7/28/2019 Basic Java Part 3

http://slidepdf.com/reader/full/basic-java-part-3 19/35Any use, copying or distribution without written permission from UnitedHealth Group is prohibited

19

Concurrency

• The word processor should always be ready to respond to keyboard and mouse events,no matter how busy it is reformatting text or updating the display. Software that can dosuch things is known as concurrent software. 

• ProcessesA process has a self-contained execution environment. A process generally has a complete,private set of basic run-time resources; in particular, each process has its own memory space.Processes are often seen as synonymous with programs or applications.

• Threads

Threads are sometimes called lightweight processes. Both processes and threads provide anexecution environment, but creating a new thread requires fewer resources than creating anew process.

A thread is a lightweight process – a single sequential flow of execution within a program

• Threads make possible the implementation of programs that seem to perform multiple tasks atthe same time (e.g. multi-threaded Web servers)

C

Page 20: Basic Java Part 3

7/28/2019 Basic Java Part 3

http://slidepdf.com/reader/full/basic-java-part-3 20/35Any use, copying or distribution without written permission from UnitedHealth Group is prohibited

20

Concurrency

Thread Lifecycle

Born

BlockedRunnable

Dead

stop()

start()

stop()

Active

block on I/O

I/O available

JVM

sleep(500)

wake up

suspend()

resume()

wait

notify

Page 21: Basic Java Part 3

7/28/2019 Basic Java Part 3

http://slidepdf.com/reader/full/basic-java-part-3 21/35Any use, copying or distribution without written permission from UnitedHealth Group is prohibited

21

Concurrency

• How to create Java Threads:

• There are two ways to create a Java thread:

1. Extend the java.lang.Thread class

2. Implement the java.lang.Runnable interface

1. Extending the Thread class

 – In order to create a new thread we may subclass java.lang.Thread and customizewhat the thread does by overriding its empty run method.

 – The run method is where the action of the thread takes place.

 – The execution of a thread starts by calling the start method.

Page 22: Basic Java Part 3

7/28/2019 Basic Java Part 3

http://slidepdf.com/reader/full/basic-java-part-3 22/35Any use, copying or distribution without written permission from UnitedHealth Group is prohibited

22

Concurrency

• Example I

class MyThread extends Thread { 

 private String name, msg; 

 public MyThread(String name, String msg) { 

this.name = name; 

this.msg = msg; 

}  public void run() { 

System.out.println(name + " starts its execution"); 

for (int i = 0; i < 5; i++) { 

System.out.println(name + " says: " + msg); 

try { 

Thread.sleep(5000); 

} catch (InterruptedException ie) {} 

System.out.println(name + " finished execution"); 

Page 23: Basic Java Part 3

7/28/2019 Basic Java Part 3

http://slidepdf.com/reader/full/basic-java-part-3 23/35Any use, copying or distribution without written permission from UnitedHealth Group is prohibited

23

Concurrency

• Example I (cont.)

public class test { 

public static void main(String[] args) { 

MyThread mt1 = new MyThread("thread1", "ping"); 

MyThread mt2 = new MyThread("thread2", "pong"); 

mt1.start(); 

mt2.start(); 

 } 

 } 

Page 24: Basic Java Part 3

7/28/2019 Basic Java Part 3

http://slidepdf.com/reader/full/basic-java-part-3 24/35Any use, copying or distribution without written permission from UnitedHealth Group is prohibited

24

Concurrency

Blocking Threads

• When reading from a stream, if input is not available, the thread will block

• Thread is suspended (“blocked”) until I/O is available 

• Allows other threads to automatically activate

• When I/O available, thread wakes back up again

 – Becomes “runnable” 

 – Not to be confused with the Runnable interface

Page 25: Basic Java Part 3

7/28/2019 Basic Java Part 3

http://slidepdf.com/reader/full/basic-java-part-3 25/35Any use, copying or distribution without written permission from UnitedHealth Group is prohibited

25

Concurrency

• Implementing the Runnable interface

• In order to create a new thread we may also provide a class that implements the java.lang.Runnableinterface

• Prefered way in case our class has to subclass some other class

• A Runnable object can be wrapped up into a Thread object

 – Thread(Runnable target)

 – Thread(Runnable target, String name)• The thread’s logic is included inside the run method of the runnable object 

Page 26: Basic Java Part 3

7/28/2019 Basic Java Part 3

http://slidepdf.com/reader/full/basic-java-part-3 26/35Any use, copying or distribution without written permission from UnitedHealth Group is prohibited

26

Concurrency

• Example II

class MyClass implements Runnable { 

 private String name; 

 private A sharedObj; 

 public MyClass(String name, A sharedObj) { 

this.name = name; this.sharedObj = sharedObj; 

 public void run() { 

System.out.println(name + " starts execution"); 

for (int i = 0; i < 5; i++) { 

System.out.println(name + " says: " + sharedObj.getValue()); 

try { 

Thread.sleep(5000); } catch (InterruptedException ie) {} 

System.out.println(name + " finished execution"); 

Page 27: Basic Java Part 3

7/28/2019 Basic Java Part 3

http://slidepdf.com/reader/full/basic-java-part-3 27/35

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited

27

Concurrency

• Example II (cont.)

class A { 

 private String value; 

 public A(String value) { this.value = value; } 

 public String getValue() { 

return value; 

 public class test2 { 

 public static void main(String[] args) { 

 A sharedObj = new A("some value"); 

Thread mt1 = new Thread(new MyClass("thread1", sharedObj)); 

Thread mt2 = new Thread(new MyClass("thread2", sharedObj)); 

mt1.start(); mt2.start(); 

Page 28: Basic Java Part 3

7/28/2019 Basic Java Part 3

http://slidepdf.com/reader/full/basic-java-part-3 28/35

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited

28

Concurrency

Thread Scheduling

• In general, the runnable thread with the highest priority is active (running)

• Java is priority-preemptive

 – If a high-priority thread wakes up, and a low-priority thread is running

 – Then the high-priority thread gets to run immediately

• Allows on-demand processing

 – Efficient use of CPU

Thread Starvation

• If a high priority thread never blocks

• Then all other threads will starve

• Must be clever about thread priority

C

Page 29: Basic Java Part 3

7/28/2019 Basic Java Part 3

http://slidepdf.com/reader/full/basic-java-part-3 29/35

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited

29

Concurrency

Thread Priorities: General Strategies

• Threads that have more to do should get lower priority

• Counterintuitive

• Cut to head of line for short tasks

• Give your I/O-bound threads high priority

 – Wake up, immediately process data, go back to waiting for I/O

Race Conditions

• Two threads are simultaneously modifying a single object

• Both threads “race” to store their value 

• In the end, the last one there “wins the race” 

• (Actually, both lose)

C

Page 30: Basic Java Part 3

7/28/2019 Basic Java Part 3

http://slidepdf.com/reader/full/basic-java-part-3 30/35

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited

30

Concurrency

• Race Condition Example

class Account { 

int balance;

public void deposit(int val)

int newBal;

newBal = balance + val;

balance = newBal;

 }

 }

C

Page 31: Basic Java Part 3

7/28/2019 Basic Java Part 3

http://slidepdf.com/reader/full/basic-java-part-3 31/35

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited

31

Concurrency

• Synchronization of Threads

• In many cases concurrently running threads share data and must consider the state andactivities of other threads.

• If two threads can both execute a method that modifies the state of an object then themethod should be declared to be synchronized, allowing only one thread to execute themethod at a time.

• If a class has at least one synchronized methods, each instance of it has a monitor. A

monitor is an object that can block threads and notify them when it is available.

Example:

public synchronized void updateRecord() { 

 // critical code goes here …

 }

• Only one thread may be inside the body of this function. A second call will be blocked untilthe first call returns or wait() is called inside the synchronized method.

C

Page 32: Basic Java Part 3

7/28/2019 Basic Java Part 3

http://slidepdf.com/reader/full/basic-java-part-3 32/35

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited

32

Concurrency

If you don’t need to protect an entire method, you can synchronize on an object: 

public void foo() {

 //… 

synchronized (this) {

 //critical code goes here … 

}

 //… 

}

• Declaring a method as synchronized is equivalent to synchronizing on this for all themethod block.

C

Page 33: Basic Java Part 3

7/28/2019 Basic Java Part 3

http://slidepdf.com/reader/full/basic-java-part-3 33/35

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited

33

Concurrency

Thread Deadlock

• If two threads are competing for more than one lock• Example: bank transfer between two accounts

 – Thread A has a lock on account 1 and wants to lock account 2

 – Thread B has a lock on account 2 and wants to lock account 1

Avoiding Deadlock

• No universal solution

• Ordered lock acquisition

• Encapsulation (“forcing directionality”) 

• Spawn new threads

• Check and back off

• Timeout

• Minimize or remove synchronization

Wait and Notify

• Allows two threads to cooperate• Based on a single shared lock object 

Conc rrenc

Page 34: Basic Java Part 3

7/28/2019 Basic Java Part 3

http://slidepdf.com/reader/full/basic-java-part-3 34/35

Any use, copying or distribution without written permission from UnitedHealth Group is prohibited

34

Concurrency

Wait/Notify Sequence

Lock Object

Consumer Thread

Producer Thread

1. synchronized(lock){

2. lock.wait();

3. produceResource()

4. synchronized(lock)

5. lock.notify();

6.} 7. Reacquire lock 8. Return from wait()

9. consumeResource();10. }

Page 35: Basic Java Part 3

7/28/2019 Basic Java Part 3

http://slidepdf.com/reader/full/basic-java-part-3 35/35

35

Thank you