You are on page 1of 83

K.V.

R Sir 11am JSE Multi Threading: II) Multithreading: Multi threading is one of the distinct feature of the java programming. The basic aim of the multi threading is to provide concurrent execution. Thread: A flow control in java is known as Thread. The purpose of thread is that execute the logic of the java program which is written in the form of user/Programmer defined methods. If a java program is containing multiple flow of controls (Threads) then it is known as multi thread program. The languages C, C++, PASCAL, COBOL e.t.c., that related applications execution environment contains single flow of control hence such languages are called single threaded modeling languages. In general single threaded modeling languages provides only sequential execution but not concurrent execution and these languages that not contain any library for development multi threading applications. The languages/technologies java/.net are treated as multi threaded modeling languages. Because the execution environment contains and provides multiple flow of controls for achieving concurrent execution. In general multi threaded modeling languages provides both concurrent and sequential execution and they contains an effective API for development of multi threading applications. In java program we have the following API for development of multithreading applications. EX: Java.lang.Thread(Class), Java.lang.Runnable(Interface). Whenever we write a java program there exists two types of threads they are i) Foreground/child Thread ii) Background/Parent Thread A foreground thread is one which is always executing the logic of java program which is written in the form of methods. A background thread which is always monitoring the execution of foreground thread(s). By default in every java program there exists single foreground thread and single background thread programmatically one can create multiple foreground threads and recommended to have one background thread per java program. The real world implementation of multithreading concept is to develop real world server softwares like Tomcat(Apache Jakarta software Foundation), web logic(BEA), web sphere(IBM) e.t.c., Hence most of the popular real world server softwares implemented in java language with the concept of multi threading. Hence multi threading concept of java is one of the specialized form of multitasking concept of OS.

Q) How do you justify each and every java program is multi threaded?
1

K.V.R Sir 11am JSE

A) Whenever we create a java program the logic of the program is executed by one of the thread is known as foreground thread. The execution starts of the foreground are monitored by one more thread is known as background thread. Hence java programming environment is containing multiple threads. Therefore every java program is multi threaded. Conclusion: Many real world server softwares developed by Server vendors in a language called Java with a concept of Multithreading. Hence Multithreading concept of Java is one of the specialized form of Multitasking concept of operating system.

Server Software Tomcat Web logic Web Sphere Oracle Application Server Glass Fish

Vendor Apache Jakarta Software foundation BEA IBM Oracle SUN Micro System e.t.c

Q) What are the differences between program and process? Program 1. A program is set of optimized instructions. 2. Program always resides in secondary memory for a long time until we delete. 3. Based on the duration of the existence of a program is treated as static Object. Process 1. A program is under exception is known as process. 2. Process resides in main memory for limited span of time until execution complete. 3. Based on the duration of the existence of a program is treated as dynamic Object.

As real world developer in any language we may develop two types of applications. They are 1. 2. 1. 1. Process based applications. Thread based applications. Process based applications Process based applications always provides single flow of control.

Thread based applications 1. Thread based applications always provides and contains multiple flow of control. 2. All the applications of Java, .NET e.t.c., are comes under process based applications. 3. Context switch is less.
2

2. All the applications of C,C++, Pascal, COBOL e.t.c., are comes under process based applications. 3. Context switch is more.

K.V.R Sir 11am JSE 4. Because of more context switch process based applications takes more execution time. 5. All the process based applications are treated as heavy weight components. 6. Process based applications provide only sequential execution but not concurrent execution. 7. For each sub program in process based applications there exists a separate address space. In the above table Address space: It is an amount of temporary memory space created by Operating System on Stack memory for temporary execution of Thread. Context Switch: The mechanism of changing the control of CPU from one address space to another address space is known as Context switch. Conclusion: For the best applications Context switch must be less. Heavy weight Components: Heavy weight components are those which always taking more processing time. Light weight Components: Light weight components are those which always taking less processing time. For each and every Thread based applications is one of the process based application which one Main process will be created and the Main process internally creates various sub processes (known as forking) In Java programming point of view main process is known as Thread group sub processes are known as foreground Threads but a process based applications are not Thread based applications. States/ Life cycle Thread: Whenever we write a multi threaded program there is possibility of existing many number of Threads. When multi threading program start executing, the threads of that program will undergo five states of Thread. They are 1. 2. 3. 4. 5. New State Ready State Running State Waiting State Halted State
3

4. Because of less context switch process based applications takes more execution time. 5. All the Thread based applications are treated as heavy light weight components. 6. Thread based applications provide both sequential and concurrent execution. 7. In Thread based applications irrespective of number of sub programs there exists a single address space.

K.V.R Sir 11am JSE Thread State Chart Diagram: Main Memory

Ready

Running

Halt

New

Wait

New State: A new state is one in which Thread is created and it is about to enter in main memory. Ready: A Ready state is one in which Thread is entered into the main memory. Memory space is created and first time waiting for CPU. Running State: A Running State is one which the Thread is under the control of CPU in Java programming Threads of Java executing concurrently. Justification: If Threads are executing hour by hour or minute by minute or second by second that type of Thread execution is known as sequential execution. If threads are executing millisecond by millisecond that type of Thread execution is known as Concurrent execution because no human being calculations may not be able to differentiable of milliseconds of time hence in Java programming all the Threads of our program executed by the CPU concurrently by following Round robin algorithm with the difference of milliseconds time. Waiting state: A state of the Thread is said to be waiting state if and only if it satisfies the following factors. a) Remaining CPU burst time (The amount of time required by the Thread from the CPU for its complete execution is known as CPU burst time). b) Suspending the currently executing the Thread.

K.V.R Sir 11am JSE c) Making the currently executing Thread to sleep for a period of time in terms milliseconds. d) Making the currently executing Thread to wait for a period of time in terms of milliseconds. e) Making the currently executing Thread to wait without specifying the period of time. f) Joining the currently executing Threads after completion of execution. 6. Halted State: A Halted State is one in which Thread has completed its execution in general as long as the Thread present in ready, running and waiting states whose execution state is true and these states are known as in memory states. As long as Threads are present in NEW and HALTED States whose execution status is false and these states are known as out memory states. Number of ways to create a Thread: In Java programming we have two ways to create a flow of control (Thread) they are i) ii) i) By using java.lang.Thread class By using java.lang.Runnable interface. Java.lang.Thread Class: By using Thread class a flow of control can be created in three ways those are a) Directly by using NEW operator. EX: Thread t1=new Thread() b) By using Factory method EX: Thread t1=Thread.CurrentThread() c) An Object of subclass of java.lang.Thread is an Object of java.lang.Thread. EX: Class th1 extends Thread { ----------------------} th t1=nw th1()

K.V.R Sir 11am JSE Here t1 is an Object of th1 and th1 is sub class of java.lang.Thread class hence t1 is indirectly an Object of java.lang.Thread class. Profile: Data members: 1. Public static final int MAX-PRIRITY(=10) 2. Public static final int MIN_PRIORITY(=1) 3. Public static final int NORM_PRIORITY(=2) The above Data members are known as Thread priority modifiers. The default priority of Thread is NORM_PRIORITY and all the priorities must be accessed by a class name. Constructors: 1. Thread(): This constructor is used for creating an Object of Thread class without giving user friendly name of the Thread. EX: Thread t1=new Thread(); Here t1 is called reference the default name of the Thread is Thread_0. In general when we create n number of Thread class Objects by using default Constructor, the default names of Thread starts from Thread-0, Thread-1 ,--------,Thread n-1 it is highly recommended not to give default names to the Thread and give user friendly names to the Threads. 2. Thread(String): Hence the String parameter represents user friendly name of the Thread. This Constructor is used for creating an Object of Thread class by passing user friendly name of the Thread. EX: Thread t1=new Thread(javath); 3. Thread(Runnable): This constructor is used for converting Runnable interface Object into Thread class Object for making use of all the methods Thread Class(Specially start()) to enter into run() of Runnable interface. Th1 t1=new Th1() (or) Runnable t1=new Th1() t.start(); //Invalid

Thread t11=new Thread(t1);

K.V.R Sir 11am JSE T11.start(); //valid 4. Thread(Runnable, String): The functionality of this Constructor is exactly similar to above Constructor but the additional functionality of this Constructor is to give user friendly Thread name. EX: Runnable t1=new Th1() Or Th1 t1=new Th1(); //t.start() invalid Thread t11=new Thread(t11,javath) String tname=t11.getName(); System.out.println(tname); //Javath

Instance methods: 1. Public final void setName(String) 2. Public final String getName() The above methods are used for setting the user friendly name to the Thread and obtaining same thing from the Thread. EX: Thread t1=new Thread() String tname=t1.getName(); System.out.println(tname); // Thread 0 T1.setName(Java th); Tname=t1.getName(); System.out.println(tname);//Java th 3. Public final void setPriority(int) 4. Public final int getPriority() The above methods are used for setting and getting the priority of the Thread. EX: Thread t1=new Thread();
7

K.V.R Sir 11am JSE Int pv=t.getPriority(); System.out.println(pv); T1.setPriority(Thread.MAX_PRIORITY) Pv=t1.getPriority(); System.out.println(pv); //100 MAX_PRIORITY 5. Public final void start(): This method is used for transferring the Thread from new state to ready state, provides internal services of multithreading and automatically calls run() which is containing the logic of the Thread. Note: The internal service of the multithreading represents providing concurrency, synchronization, inter thread communication e.t.c., 6. Public void run(): i. It is one of the non final method present in Thread class for providing logic of the Thread. Originally run () defined in Thread class with null body method. ii. As a Java programmer to provide a logic of the Thread, run() must be overridden in the context of our derived class by extending java.lang.Thread class. iii. This method will be called automatically by start () upon the Thread class Object we apply start (). That is run () cant be called by the Java programmer directly because that particular Thread never get the services of multithreading. EX: class th1 extends Thread { Public void run() { -------------------} } While we are overriding run() of the Thread class either we write block of statements which provides the logic of the Thread or we call user defined method which contains the logic of the Thread.
8

K.V.R Sir 11am JSE Th1 t=new Th1(); //new state T1.start(); //enter into ready state. 7. Public boolean isAlive(): This method determines the execution states of the Thread. This method returns true provided Thread is present in ready, running and waiting state. This method returns false when the Thread is in NEW and HALTED states. Th1 t1=new Th1() Systm.out.println(execution states of t1=+t1.isAlive());//F T1.start(); System.out.println(Execution states of t1=+t1.isAlive()); //T } 8. Public final void suspend (): This method is used for suspending currently executing Thread. When the Thread is suspended, the Thread will be entered into waiting state from running state and save temporary result of the Thread the PCB(Process control block) PCB: PCB is a buffer created for each and every Thread by the Operating System when the Thread is entered into ready state first time. 9. Public final void resume (): This method is used for bringing the Thread from waiting state to ready state. When the Thread is resumes it starts executing where it left off. Before its suspension by retrieving temporarily result of Thread from PCB. 10. Public final void stop (): This method is used for stopping the current execution of the Thread. When the Thread stopped its execution into Halted state from running state. When the Thread is restarted it start executing from the beginning. 11. *public final void join() throws java.lang.InterruptedException: This method is used for joining threads which are completed their execution as a single Thread. In another words this method joins the completed Thread group name collects all the combined joined Threads and handover to garbage Collector this approach improves the performance of multi Threading applications. The default environment of Java says as and when individual Threads are completed their execution individually collected Thread group name and handover to garbage collector which is not a recommended process. Interrrupted exception occurs, interrupted exception never occurs in single/standalone applications but there is a possibility of occurring in Client/server environment. Lets assume n Threads are stated their execution and n-1 Threads are completed their execution and joined. Still nth Thread is executing due to mis memory management of serverside Operating System, Thread group name is trying collect n-1 joined Threads
9

K.V.R Sir 11am JSE and handovering to garbage collector even through nth Thread is under execution. In this point of time JVM generates a predefined exception called java.lang.Interrupted Excetion with respective nth Thread. Interuppted Exception is one of the CheckedException. -----------------------------try { t1.join() t2.join() t3.join() } catch(InterruptedException ir) { System.out.println(Problem in Thread execution); } Static methods: 1. Public static final Thread currentThread(): This method is used for obtaining the Threads which are by default running EX: Thread t1=Thread.currntThread() Sysem.out.println(t1); //Thread(main, 5, main) FGT Priority TGN (FGT-Foreground Thread) (TGN-Thread Group Name) T1.setName(Java th); System.out.println(t); // Thread(javath, 5, main) 2. Public static final void sleep(long milliseconds) throws InterruptedException This method is used for making the currently executing Thread to sleep for a period of time in terms of milliseconds 1 sec=1000 milliseconds If the sleeping time is completed, then the Thread will be entered into ready state. When interrupted exception occurs: Let us assume sum of the Threads of current Java program sleeping in the server memory if some other program Threads are trying to sleep
10

K.V.R Sir 11am JSE in the same place where the previous program Threads are sleeping then JVM generates a predefined exception called java.lang.InterruptedException with respective the previous Threads we know that interrupted exception never occurs in standalone single maching but they always occurs in Client/Server architecture. --------------------------try { Thread.sleep(1000) } Catch(InterruptedException ie) { System.err.println(problem in Thread execution); } P) Write a Java program which will print preliminary information about the Thread such as the Thread which are by default running, execution status of the default Threads, default name of the Foreground Thread, execution status of the Foreground Thread, Thread priority modifier values e.t.c., class Thdemo { public static void main(String args[]) { Thread t1=Thread.currentThread(); System.out.println("default thread names="+t1); // Thread[main,5,main] t1.setName("javath"); System.out.println("default Thread name after mod="+t1); System.out.println("execution states of default Thread="+t1.isAlive());
11

K.V.R Sir 11am JSE Thread t2=new Thread(); System.out.println("default name of F.G Thread="+t2.getName()); //Thread-0 System.out.println("execution States of F.G Thread="+t2.isAlive()); //false System.out.println("Value of Maximum priority="+Thread.MAX_PRIORITY); System.out.println("Value of Minimum priority="+Thread.MIN_PRIORITY); System.out.println("Value of Normal priority="+Thread.NORM_PRIORITY); } } /*OUTPUT C:\>java Thdemo default thread names=Thread[main,5,main] default Thread name after mod=Thread[javath,5,main] execution states of default Thread=true default name of F.G Thread=Thread-0 execution States of F.G Thread=false Value of Maximum priority=10 Value of Minimum priority=1 Value of Normal priority=5 */ Internal flow of the Threads: When we write any multithreading program there is a possibility of containing multiple Threads. When Java multithreaded program is under execution then all the Threads will internally executes by following steps. 1. Java program starts executing 2. JVM creates a ThreadGroupname(TGN) and it always resides in main(). 3. TGN Creates Foreground Threads (Foreground Threads are mean for running and executing in RUN()).

12

K.V.R Sir 11am JSE 4. ThreadGroupName dispatches the Foreground Threads to their respective RUN methods(by using start()) 5. Foreground Thread executes RUN () and gives result to ThreadGroupName either all at once or one by one. 6. TGN receives the result of Foreground Threads either all at once or one by one. 7. TGN gives the result of the Java program to the application user either all at once or one by one. 8. TGN collects all Foreground Threads and handover to Garbage Collector. 9. JVM Collects TGN and handover to garbage collector. 10. The Java program stops executing (because there are no more Threads resides in Java Environment). P) Write a Java program which will print 1 to 10 numbers after each and every second. class th1 extends Thread { public void run() { try { for(int i=1;i<=10;i++) { System.out.println(i); Thread.sleep(1000); } } catch(InterruptedException ie) { System.out.println("Probability in Thread execution"); }

13

K.V.R Sir 11am JSE } } class Thdemo { public static void main(String args[]) { th1 t1=new th1(); System.out.println("execution status of before start="+t1.isAlive()); t1.start(); System.out.println("execution status of t1 after start="+t1.isAlive()); try { Thread.sleep(11000); } catch(InterruptedException ir) { System.out.println("Probability in Thread execution"); } System.out.println("execution of t1 after completion ="+t1.isAlive()); } } OUTPUT /*OUTPUT

14

K.V.R Sir 11am JSE C:\>java Thdemo execution status of before start=false execution status of t1 after start=true 1 2 3 4 5 6 7 8 9 10 execution of t1 after completion =false */ By using java.lang.Runnable: Runnable is one of the Predefined interface present in java.lang.Package this is containing only one method and whose prototype is given below. Public abstract void run(): We know that run() of Thread class defined with null body and run() of Runnable interface belongs to abstract. Industry is highly recommended to override run() of runnable interface. P) Write a Java program which will print 1 to 10 numbers after each and every second. class th1 implements Runnable { public void run() { try
15

K.V.R Sir 11am JSE { for(int i=1;i<=10;i++) { System.out.println(i); Thread.sleep(1000); } } catch(InterruptedException ie) { System.out.println("Probability in Thread execution"); } } } class thdemo1 { public static void main(String args[]) { Runnable t11=new th1(); Thread t1=new Thread(t11,"javath"); //th1 t12=new th1(); //Thread t1=new Thread(t12,"javath"); System.out.println("name of the Thread="+t1.getName()); System.out.println("execution status of t11 before start="+t1.isAlive()); t1.start();

16

K.V.R Sir 11am JSE System.out.println("Execution status of t11 after start="+t1.isAlive()); } } /* OUTPUT name of the Thread=javath execution status of t11 before start=false Execution status of t11 after start=true 1 2 3 4 5 6 7 8 9 10 */ EX:2 class th5 implements Runnable { public void run() { try

17

K.V.R Sir 11am JSE { for(int i=1;i<=10;i++) { System.out.println(i); Thread.sleep(100); } } catch(InterruptedException ie) { System.err.println("Catched Interrupted Exception"); } } } class thdemo4 { public static void main(String args[]) { Runnable t1=new th5(); Thread t2=new Thread(t1,"Jaspp"); System.out.println("Thread Current state="+t2.isAlive()); t2.start(); System.out.println("Thread Current state="+t2.isAlive()); try {

18

K.V.R Sir 11am JSE t2.sleep(1100); } catch(InterruptedException ie1) { System.err.println("Hello"); } System.out.println("Thread Current state="+t2.isAlive()); } } /* Thread Current state=false Thread Current state=true 1 2 3 4 5 6 7 8 9 10 Thread Current state=false */

19

K.V.R Sir 11am JSE P) Write a Thread based application for computing sum and subtraction of two numbers with Threads. class th1 extends Thread { int a,b,c; void set(int a, int b) { this.a=a; this.b=b; } public void run() { c=a+b; System.out.println("sum in th1="+c);

} } class th2 implements Runnable { int a,b,c; void set(int a, int b) { this.a=a; this.b=b;

20

K.V.R Sir 11am JSE } public void run() { c=a+b; System.out.println("sub in th2="+c); } } class thdemo { public static void main(String args[]) { int x=Integer.parseInt(args[0]); int y=Integer.parseInt(args[1]); th1 t1=new th1(); th2 t2=new th2();

t1.set(x,y); t2.set(x,y); Thread t11=new Thread(t2); t1.start(); t11.start(); //join the Threads try {

21

K.V.R Sir 11am JSE t1.join(); t11.join();

} catch(InterruptedException ie) { System.out.println("Prob in Thread execution"); } System.out.println("Execution status of t1 after join="+t1.isAlive()); System.out.println("Exectuiont status of t11 after join="+t11.isAlive()); } } /*OUTPUT sum in th1=5 sub in th2=5 Execution status of t1 after join=false Exectuiont status of t11 after join=false */ P) Write a Thread based program for implementation for banner animation and scrolling a given message. import java.awt.*; import java.applet.*; /*<applet code="scroll1" height=300 width=300></applet>*/ public class scroll1 extends Applet implements Runnable {
22

K.V.R Sir 11am JSE String msg="WEL COME TO JAVA."; public void init() { setBackground(Color.CYAN); setForeground(Color.RED);

} public void start() { Thread t=new Thread(this); //this refers to currnet class Object. Which implements runnable interface into Thread class Object t.start();

} public void paint(Graphics g) { Font f=new Font("arial",Font.BOLD,60); g.setFont(f); g.drawString(msg,100,100); } public void run() { try {
23

K.V.R Sir 11am JSE while(true) { char ch=msg.charAt(0); msg=msg.substring(1,msg.length()); msg=msg+ch; Thread.sleep(1000); repaint(); } } catch(InterruptedException ie) { System.err.println("problem in Thread"); } } }

P) Write a Thread based application which will generate number automatically. import java.awt.*; import java.applet.*; /*<applet code="scroll" height=300 width=300></applet>*/ public class scroll extends Applet implements Runnable { int i=0; public void init()

24

K.V.R Sir 11am JSE { setBackground(Color.CYAN); setForeground(Color.RED);

} public void start() { Thread t=new Thread(this); //this refers to currnet class Object. Which implements runnable interface into Thread class Object t.start();

} public void paint(Graphics g) { Font f=new Font("arial",Font.BOLD,60); g.setFont(f); g.drawString(String.valueOf(i),100,100); } public void run() { try { while(true) {
25

K.V.R Sir 11am JSE i++; repaint(); Thread.sleep(1000); } } catch(InterruptedException ie) { System.err.println("problem in Thread"); } } }

Synchronization Techniques: 1. Synchronization is one of the distinct feature of multithreading to eliminate inconsistent results. 2. The concept of Synchronization must be always applied on common tasks for getting consistent results that is if multiple Threads are performing common task then those Threads generates inconsistent result. To avoid this inconsistent result it is recommended to apply Synchronization concept. DEF: The mechanism of allowing only one Thread among multiple Threads into the area which is sharable/common to perform read and write operations known as Synchronization. Need of Synchronization: 1. Let us assume variable balance whose initial value is 0. Let us assume there exists two types of Threads t1 and t2 want to update or deposit `10 and if `20 to the balance variable respectively.
26

K.V.R Sir 11am JSE 2. Both Threads shared execution and completed if verify the value of the balance variable then it contains either 10 or 20. Which is one of the inconsistent result. 3. To avoid this inconsistent result we must apply the concept of Synchronization. Synchronization concept applied: 1. Threads t1 and t2 started their execution (Assume t1 starts first and t2 starts later with the different of milliseconds of time). Thread t1 gets the value of balance(0) and balance variable value will be locked by JVM until t1 completes its execution. 2. Maintenance if Thread t2 trying to access the balance variable value then the JVM made the Thread t2 to wait until t1 completes its execution. 3. Once the Thread t1 completes its execution balance variable value(10) will be unlocked and given to t2 and once again balance variable value will be locked. 4. Thread t2 completed its execution, balance variable value(30) will be unlocked. Finally it we observer the value of the balance then it contains consistent result(30). 5. Hence during the Synchronization concept the process of locking and unlocking will be performed by the JVM until all Threads completed their execution. 6. Thread synchronization techniques are divided into two types they are i. Synchronization Methods ii. Synchronized blocks. i. Synchronized Methods: If any ordinary method is accessed by more than one Thread then the ordinary method generates an inconsistent result. To avoid this inconsistent result the definition of ordinary method must be preceded by a keyword synchronized for making the method as Synchronized. Based on Synchronized keyword we write before the methods, they are classified into two types they are a) Synchronized instance methods. b) Synchronized static methods. a) Synchronized instance methods: If an Ordinary instance method is accessed by multiple Threads then there is possibility of getting inconsistent result. To avoid this inconsistent result, the ordinary method must be made as synchronized by using synchronized keyword. Syn: Synchronized ReturntypeMethodName(list of formal params if any) { Block of Statement(s); }

27

K.V.R Sir 11am JSE If we make an ordinary instance method as synchronized then the object of corresponding class will be locked by JVM. Class Account { Private int amount; System.out.println(currbal=+bal); } } As long as the Thread is executing the above deposit method then the object of account class will be locked. b) Synchronized static methods: If an ordinary static method accessed by multiple Threads then there is possibility of getting in consistent result. To avoid this inconsistent result the ordinary static method definition must be made as synchronized by using synchronized keyword. Syn: Synchronized static method name(list of formal params if any) { Block of statement(s); } If we make any ordinary static method as synchronized then corresponding class will be locked. EX: class Account { Synchronized static void deposit(int amt) { bal=bal+amt;
28

K.V.R Sir 11am JSE System.out.println(currbal=+bal); } } As long as the Thread is executing the above synchronized static method then Corresponding class will be locked. Synchronized blocks: Synchronized blocks are an alternative synchronization for achieving consistent results instead of using synchronized methods. Synchronized blocks must be always return ordinary instance methods and ordinary instance methods inherited non static methods for achieving the consistent result. Synchronized(object of current class) { Block of statement(S); } Synchronized blocks always locks object of the class but not class because we override instance methods only but not recommended to static methods. Need of Synchronized blocks: If a derived class inherits any method from an interface and if the inherited ordinary instance method is accessed by multiple Threads with respect to the derived class Object then the inherited ordinary instance method generates inconsistent result. To avoid this inconsistent result, as a derived class programmer, we may attempt to write synchronized keyword before ordinary inherited instance method. This attempting is not possible because the derived class programmer does not have any privileges to change the prototype because interface methods. We are unable to solve inconsistent problem with concept of Synchronized methods. Hence to solve the problem of Synchronized methods and to get consistent result we have a concept synchronized blocks. EX: //Account package ap;

29

K.V.R Sir 11am JSE public interface Account { void deposit(int amt); } Class savings implements ap.Account { private int bal=0; public voud deposit(int amt) { Account.class

Synchronized(this) {

Synchronize block.
Bal=bal+amt;

.
System.out.println(current bal=+bal);

P) write a Java program which illustrate the concept of Synchronization( Let us assume there exists an account class with a variable balance and whose initial value is 0 Account class must contain a method for depositing and a method for verifying the balance. Let us assume there exists n number of customers (Threads) who would like to deposit `10 each in balance of Account class concurrently during concurrency ensure that balance of Account class must contain consistent result). class Account { private int bal=0; synchronized void deposit(int amt)
30

K.V.R Sir 11am JSE { bal=bal+amt; System.out.println("Current bal="+bal); } int getbal() { return bal; } } class cust extends Thread { Account ac; cust(Account ac) { this.ac=ac; } public void run() { ac.deposit(10); } } class sync { public static void main(String args[])

31

K.V.R Sir 11am JSE { //create single instance of Account Account ac=new Account(); //create array of Cust class as Threads cust cu[]=new cust[5]; //give the single ref of Account class to array of customers for(int i=0;i<5;i++) { cu[i]=new cust(ac); } //start the array of the customers for deposits `10

for(int i=0;i<5;i++) { cu[i].start(); } //join the array of the customers try { for(int i=0;i<5;i++) { cu[i].join(); } }

32

K.V.R Sir 11am JSE catch(InterruptedException ie) { System.out.println("problem found in Thread execution"); } //print the total val System.out.println("TOTAL BAL="+ac.getbal()); } } /*OUTPUT Current bal=10 Current bal=20 Current bal=30 Current bal=40 Current bal=50 TOTAL BAL=50 */ NOTE: If we wont give any synchronized keyword then it will execute and also give consistent result but not follow order. 2. Due to operation System it will give consistent result. 3. The operating System should be distributed then it will give consistent result. Because internally OS follows Synchronization technique. 4. The operating systems (Windows 95, DOS) are not following synchronization technique. 1. The result without Synchronized keyword: Current bal=10 Current bal=50

33

K.V.R Sir 11am JSE Current bal=40 Current bal=30 Current bal=20 TOTAL BAL=50 Same program with interfaces: //Package Creation package ap; public interface acc { public void deposit(int amt); }

Program:

import ap.acc; class Account implements acc { private int bal=0; public void deposit(int amt) { synchronized(this) { bal=bal+amt;

34

K.V.R Sir 11am JSE System.out.println("Current bal="+bal); } } int getbal() { return bal; } } class cust extends Thread { Account ac; cust(Account ac) { this.ac=ac; } public void run() { ac.deposit(10);

} } class sync1 { public static void main(String args[])

35

K.V.R Sir 11am JSE { //create single instance of Account Account ac=new Account(); //create array of Cust class as Threads cust cu[]=new cust[5]; //give the single ref of Account class to array of customers for(int i=0;i<5;i++) { cu[i]=new cust(ac); } //start the array of the customers for deposits

for(int i=0;i<5;i++) { cu[i].start(); } //join the array of the customers try { for(int i=0;i<5;i++) { cu[i].join(); } }

36

K.V.R Sir 11am JSE catch(InterruptedException ie) { System.out.println("problem found in Thread execution"); } //print the total val System.out.println("TOTAL BAL="+ac.getbal()); } } /*OUTPUT Current bal=10 Current bal=20 Current bal=30 Current bal=40 Current bal=50 TOTAL BAL=50 */ Inter Thread Communication: ITC of Java is one of the specialized concept of inter process communication of Operating System. 1. ITC applications of Java are the fastest applications in the real industry compare to any of the applications in any language. 2. The real time implementations of ITC are a) Implementation of real world server software by third party vendors. b) Implementation of universal protocols such as http, FTP, SMTP e.t.c., Def: The mechanism of exchanging the data/information among multiple Threads is known as Inter Thread Communication (OR) If the output of first Thread is given as input to second Thread, the output of second Thread is given to the input to Third Thread e.t.c., then the communication between first, second and third Threads are known as Inter Thread Communication. In order to develop Inter Thread
37

K.V.R Sir 11am JSE Communication based applications we use the methods of java.lang.Object class. These methods are known as Inter Thread Communication. Methods in java.lang.Object: 1. public void wait( long milliseconds ) throws interruptedException: This method is used for making the Thread to wait for a period of time in terms of milliseconds. If the wailting time completed, automatically the Thread will be entered into Ready state from waiting state. This method is not recommended to use by Java programmer for making the Thread to wait for an amount of time because Java programmer cant decide the CPU burst time of previous Thread to wait. 2. public void wait(): This method is used for making the Thread to wait without specifying any time. 3. public void notify(): This method is used for transferring one Thread at a time from waiting state to Ready state. 4. public void notifyAll(): This method is used for transferring all the Threads into the form waiting state. The classical example of itc are i) Producer Consumer problems ii) Dining Philosophers problem iii) Readers writers problem iv) Barbershop Problem Implementation of Producer Consumer Problem: Producer: Producer is one of the Thread which will produce only one item at a time no two consecutive numbers to be produced by producer. Whatever the items are produced by producer which are consumed by consumer. Consumer: Consumer is also one of the Thread present in Java which will always consumers only one item at a time but not multiple items. Consumer is going on consuming the items which are produced by the producer if we are able to establish the consistent communication between producer and consumer Threads then it is known as Inter Thread Communication then the following diagram gives implementation of producer consumer problem.
Wait state

Wait State

Wait()
Ready State False

Q =new Q()
Boolean ValSet int n();

Wait()
Ready State

Synchronized put int() 38 Synchronized get int()

K.V.R Sir 11am JSE


Running State Running State

synchronized void put(int i)

synchronized void get()

Producer

Consumer

notify() notify()

Thread

ValSet=false

Thread

ValSet=false

P) Implement a Java program for Producer Consumer Problem. class Q { int n; boolean ValSet=false; synchronized void put(int i) { if(ValSet) { try { wait();

39

K.V.R Sir 11am JSE

} catch(InterruptedException ie) { System.err.println("Problem in thread exceution");

} } else {

n=i; ValSet=true; System.out.println("put="+n); notify(); } } synchronized int get() { if(!ValSet) { try { wait();

40

K.V.R Sir 11am JSE

} catch(InterruptedException ie) { System.err.println("Problem in Thread"); } } else { System.out.println("got="+n); ValSet=false; notify(); } return(n); } } class producer implements Runnable { Q q; producer(Q q) { this.q=q; Thread t1=new Thread(this); t1.start();

41

K.V.R Sir 11am JSE } public void run() { int i=0; while(true) { q.put(i++); } } }

class consumer implements Runnable { Q q; consumer(Q q) { this.q=q; Thread t1=new Thread(this); t1.start(); } public void run() { int i=0;

42

K.V.R Sir 11am JSE while(true) { i=q.get(); } } }

class conpro { public static void main(String args[]) { Q q=new Q(); producer po=new producer(q); consumer co=new consumer(q); } } /*OUTPUT put=4572 got=4572 put=4574 got=4574 put=4576 got=4576 put=4578

43

K.V.R Sir 11am JSE got=4578 put=4580 got=4580 put=4582 got=4582 put=4584 */ Note: This will go on execute. So we would like to stop it press Ctrl+C.

File Programming or Stream handling: Especially in the context of File Programming, we have two types of Java applications they are 1. Volatile /non-persistent applications 2. Non Volatile /persistent applications 1. Volatile/non persistent applications: i. It is one in which result of such program stored in the main memory/primary memory (RAM). ii. We know that whatever the data stored in main memory that data is temporary. iii. A persistent program is one whose basic aim is to store the temporary data permanently in the secondary memory (Hard disk). iv. In Information Technology Data persistency achieved in two ways they are a) Through Files Concept b) Through Database Concept If we store the data permanently in the form of files can be manipulated by any un authorized user. Because files concept of any programming language does not provide any security to the data in the file in the form of user names and passwords. Hence industry never recommends to achieve the data persistency through the files. Industry is highly recommended to store data
44

K.V.R Sir 11am JSE permanently in the form of Database softwares. Because of most of popular Database provides user names and passwords as an inbuilt security for protecting un authorized modifications. In order to deal with file programming of JSE we must import a predefined package called java.io.* File: A File is a Collection of Records. EX: Student 10 20 30 Sathya Ravi Raju 99.99 88.88 77.77

Files are always resides in Secondary memory. File names are always useful for future identification for retrieving and storing the Data. Record: Collection of field values is known as Records. (10, Sathya, 99.99) is known as Record. In Java programming every real world application of a file will be treated as an Object and every Object of Java which resides in main memory can be stored as a record in file. Stream: The flow of data/bytes/bits between primary memory and secondary memory is known as Stream. Types of operations on Files: On files we can perform two types of operations they are 1. Write operation/output Stream 2. Read Operation/ Input Stream 1. Write Operation: The basic aim of write operation is to transfer the data from primary memory to secondary memory. In order to perform write operation, we need to perform the following sequence of steps. i) Choose the file name. ii) Open file name in write mode iii) Perform the cycle of write operations While we are performing write operation, we get the following consequences a) Trying to write the data into the file of secondary memory where there is no enough space in the secondary memory. b) Trying to write the data on Read only files because of these two consequences we get a predefine exception called java.io.IOException

45

K.V.R Sir 11am JSE Read operation: The basic aim of Read operation is to transfer the data of the file secondary memory in the primary memory. To perform Read operation, we need to perform the following sequence of steps. i) Choose the filename ii) Open the file name in Read mode iii) Perform cycle of Read operations iv) While we are performing Read operation we get the following consequences. 1. Trying to open a file which is not existing in secondary memory because of this consequence we get a predefined exception called java.io.Exception. 2. Trying to read data from corrupted files(Corrupted files exist in secondary memory to read because of its corruption). Due to this consequence we a predefined exception called java.io.Exception. Hence in File programming of Java we get FileNotFoundException and IOException. FileNotFoundException is one of the sub exception of IOException. So that FileNotFoundException must be handled first and at least we must handle IOException these two exceptions are known as Checked Exceptions. Types of Streams in Files: Based on transferring data between primary memory and secondary memory, Streams are classified into two types those are i) ii) i) Byte Streams Character Streams. Byte Streams: Based on the transferring data between primary memory and secondary memory, streams are classified into two types those are a) Byte Streams: Byte Streams transfer the data between primary memory and secondary memory with 1 byte transferring of data between primary memory and secondary memory is known as Byte Streams. Byte Streams contains two catageories of classes. Some catageories of classes participates in write operation which will transfer 1 byte at a time from primary memory to secondary memory other catageory of classes participates in read operation from secondary memory to primary memory. Byte streams are not that much effective streams compared to other streams because of Data transfer rate of byte streams is less ByteStreams is less. BiteStream of Hierarchy Chart: In the above hierarchy chart class 1 is one of the super class for all classes in Java. The classes 2,3,4,5 are predefined abstract classes reserved by SUN Micro system for future innovations in file programming. The classes 6,7,8,9 are the bottom most concrete classes developed by SUN Microsystem both for reading and writing operations on the files. So as a Java file programmer we make use of the classes 6,7,8,9. FileInputStream class used for opening the file in read mode. In other words opening a file in read mode is nothing but creating an Object of FileInputStream class.
46

K.V.R Sir 11am JSE

3 2 InputStream FilteredInputStr eam

FileInputStream

R
1 Object

E A D W
4 8 5 FileOutputStream FileteredOutput Stream DataOutputStream DataInputStream

R I T E
OutputSteam

9 47

K.V.R Sir 11am JSE

Profile: Constructor: 1. FileInputStream(String) throws FileNotFoundException, IOException: This constructor is used for creating an Object of FileInputStream class by passing name of file to be opened in read mode. EX: open Student.data file in read mode. FileInputStream fis=new FileInputStream(student.data); If student.data is found in secondary memory then it will be successfully opened in read mode and whose address is placed in the Object of FileInputStream. Diagramatically. Student.data
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------1

File
xxx

When the file is opened successfully in the read mode, an Object of FileInputStream is positioning entry of the File and it will be automatically advanced when the reading is in progress until end of the file is reading in Java programming(end of file indicated by -1) If student.data file is not found in secondary memory then an Object of FileInputStream contains null. Hence JVM throws a predefined exception called java.io.FileNotFoundException.
null

FileNotFound Instance Methods:

48

K.V.R Sir 11am JSE 2. Public xxx readXxx: This method is one of the predefined generalized method for reading allfundametal values opened in read mode. Here Xxx represents any fundamental datatype. 3. Public int read(): This method is used for reading method 2 values of a file until end of the file is taking palce. 4. Public String readLine(): This method reading the data of a file in the form of String type. 5. Public void close(): This method is used for closing the file which is opened in read mode. FileOutputStream: The basic aim of FileOutputStream class is to open in write mode in otherwords opening the file in write mode is nothing but creating an Object of FileOutputStream. Profile: Constructors: 1. FileOutputStream(String) throws IOException 2. FileOutpurStream(String) throws IOException The above two constructors are used for opening the file in write mode by considering whether it is existing or not existing or appending or overlapping the data. Case(i): If file name is not existing and boolean=true or false Ans: The choosen file is opened successfully in write mode and an Object of FileOutputStream is pointing to the Starting entry of the file. 1) FileOutputStream fos=new FileOutputStream(student.data); (OR) 2) FileOutputStram fos=new FileOutputStream(student.data,false) 3) FileOutputStream fos=new FileOutputStream(student.data,true) Student.data fos
xxx

49

K.V.R Sir 11am JSE

Case(ii): If filename is already existing and boolean=false then Ans: The existing file will be opened in write mode and the existing data overlaps with new data

Student.data
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

File
xxx

Overlapping Data

Existing Data

Case(iii): If file name is already existing and boolean = true then the existing file will be opened in write mode and now data appends to existing data. EX: FileOutputStream fos=new FileOutputStream(student.data,true)

Student.data
--------------------------------------------------------------------------------------------------------50 -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

K.V.R Sir 11am JSE File


xxx

Existind Data Appends new Data

Instance methods: 3. 4. 5. 6. Public void writeXxx(xxx value) Public void writeLine(String) Public void close() Public void write(xxx)

Methods 3 and 6 are used for writing fundamental data to file which is opened in write mode. Method 4 is used for writing String data to the file. Method 5 is used for closing the file which is opened in write mode. P) Write a Java program which will perform the following a) Create a file and write 1 to 10 numbers. b) Open a file and print 1 to 10 numbers. import java.io.*; class Datawrite { public static void main(String args[]) { try { //step-1 String fname=args[0];

51

K.V.R Sir 11am JSE //step-2 FileOutputStream fos=new FileOutputStream(fname,true); //step-3 for(int i=1;i<=10;i++) { fos.write(i); } System.out.println("data written to the fos"); fos.close(); } catch(IOException ie) { System.err.println("unable to Open file"); } catch(ArrayIndexOutOfBoundsException ae) { System.err.println("Please enter file name"); } catch(Exception e) { System.err.println(e); } } }

52

K.V.R Sir 11am JSE

Data Read: import java.io.*; class Dataread { public static void main(String args[]) { try { //step-1 String fname=args[0]; //step-2 FileInputStream fis=new FileInputStream(fname); //step-3 int i; while((i=fis.read())!=-1) { System.out.println(i); }

System.out.println("data written to the fos"); fis.close(); } catch(IOException ie)

53

K.V.R Sir 11am JSE { System.err.println("unable to Open file"); } catch(ArrayIndexOutOfBoundsException ae) { System.err.println("Please enter file name"); } catch(Exception e) { System.err.println(e); } } } //OUTPUT

C:\>javac Dataread.java

C:\>java Dataread Please enter file name

C:\>java Dataread ksk.java 1 2 3

54

K.V.R Sir 11am JSE 4 5 6 7 8 9 10 data written to the fos C:\>type ksk.java P) Write a Java program which will copy the content of one file into another file or implement copy command of DOS. import java.io.*; class Datawrite { public static void main(String args[]) { try { //step-1 String fname=args[0]; //step-2 FileOutputStream fos=new FileOutputStream(fname,true); //step-3 for(int i=1;i<=10;i++)
55

K.V.R Sir 11am JSE { fos.write(i); } System.out.println("data written to the fos"); fos.close(); } catch(IOException ie) { System.err.println("unable to Open file"); } catch(ArrayIndexOutOfBoundsException ae) { System.err.println("Please enter file name"); } catch(Exception e) { System.err.println(e); } } } OUTPUT:

C:\>java Sathyacp prs srs.java prscontent copied into dfile

56

K.V.R Sir 11am JSE Q) Can we write try and catch blocks in finally block? Give reason A) Yes, Whichever class/interface in java throws or generates an exception and if we refer those Objects anywhere else in Java program(specially in finally block) then those Objects must be always written in try and catch blocks otherwise we will get Compile time error. P) Write a Java program which will display the content of the file or implement type command of DOS. import java.io.*; class Sathyatype { public static void main(String args[]) { if(args.length!=1) { System.out.println("Invalid syntax"); } else { FileInputStream fis=null;

try { String sfile=args[0];

fis=new FileInputStream(sfile);

int i;
57

K.V.R Sir 11am JSE while((i=fis.read())!=-1) { char ch=(char)i; System.out.println(ch);

} }

catch(FileNotFoundException ae) { System.err.println("Please enter file name"); }

catch(IOException ie) { System.err.println("unable to Open file"); }

catch(Exception e) { System.err.println(e); } } }

58

K.V.R Sir 11am JSE } DataInputStream: The basic aims of DataInputSteams class are 1. To read the data from keyboard(local reading) 2. To read the data between multiple machines which are located either in same network or in different network(global reading). Profile: 1. DataInputStream(InputStream) throws IOException, FileNotFoundException 2. Public xxx readXxx() 3. Public String readLine() Creating an Object of DataInputStream class by passing an Object of InputStream class. An Object of InputStream class in created in System class as a static data member. System.in will give the control of keyboard. EX: DataInputStream dis=new DataInputStream(System.in). Method-2 is used for reading any fundamental data between multiple machines which are located in same network or in different network. Here xxx represents any fundamental datatype. Method-3 is used for reading any kind of data in the form of String between multiple machines. DataOutputStream: The basic aim of DataOutputStream class is to write the data between multiple machines which are located in same network or different network (global writing). Profile: Constructor: 1. DataOutputStream(OutputStream) throws IOException Instance Methods: 2. Public void write Xxx(xxx values) 3. Public void writeLine(String) Constructor 1 is used for creating an Object of DataOutputStream by passing an Object of OutputStream class. This class Object allows us to write the data between multiple machine which located in the same network or different network. Method-2 is used for writing fundamental data between multiple machines. Here Xxx represents fundamental datatype.
59

K.V.R Sir 11am JSE Method-3 is used for writing String data between multiple machines. P) Write a Java program to read Data form Keyboard by making use of DataInputStream class. import java.io.*; class Sathyatype { public static void main(String args[]) { try { DataInputStream dis=new DataInputStream(System.in); System.out.println("Enter first number"); String s1=dis.readLine(); System.out.println("Enter second number"); String s2=dis.readLine(); int res=Integer.parseInt(s1)+Integer.parseInt(s2); System.out.println("The result is ="+res); } catch(Exception e) { System.err.println(e); } } }

60

K.V.R Sir 11am JSE Note: It is highly recommended to use Scanner class to read the data from keyword instead of using DataInputStream class. Serialization: DEF: The process of storing/saving the content of the entire object at a time to the file of secondary memory by performing single write operation is known as serialization. Serialization concept always participates in write operation. 1. If we execute any Java program then the result of Java program is available in the form of Object and whose data is temporary. 2. If the Object is containing multiple values and to store those Object values permanently in the file of secondary memory then by using normal programming of Java it takes multiple write operations. 3. It is one of the time consuming process and performance of file programming is reduced. To improve the performance of file programming multiple values of objects at a time to the file secondary memory, we use the concept of serialization. Advantage: The advantage of serialization concept is that with a single write operation all the values of the object stored in the form of the file in secondary memory. De-serialization: DEF: The ability to restore the entire records of a file of secondary memory into secondary memory with a single read operation is known as De-serialization. De-serialization concept always participates in read operation. 1. We know that file is a collection of records and a record is collection of field values if we want to read a record which is containing multiple values then by using ordinary file programming we need to perform multiple read operations. 2. Which is one of the time consuming process and performance of such applications will be reduced to eliminate this problem we must use the concept of De-serialization. Advantage: In other words the advantage of De-serialization is that with the help of single read operation, the entire record of a file will be transferred from file of secondary memory into primary memory. Phases in serialization and De-serialization application development: In order to develop any applications related to serialization and De-serialization concepts, that application development contains three phases they are i) ii) Development of Serialization sub class Development of serialization process.
61

K.V.R Sir 11am JSE iii) Development of De-serialization process

Development of Serializable sub class: Which ever class Object participating in serialization process and De-serialization process that class definition must implements a predefined interface called java.io.serializable which ever user defined class is implementing java.io.serializable interface, that user defined class is known as Serializable sub class. Java.io.serializable is one of the marker or tagged interface because it does not contain any abstract methods. Definition of Marker interface: A Marker interface is one which does not contain any abstract methods. EX: 1. 2. 3. 4. 5. java.io.serializable java.lang.cloneable javax.rni.Remote javax.servlet.singleThreadModel javax.ejb.EJBHome e.t.c.,

Steps for developing serializable sub class: 1. Choose an appropriate package and ensure that it should be first executable statement and place serializable sub class for common access. 2. Choose an appropriate user defined sub class and ensure whose modifier must be public and this class is going called as serializable sub class. 3. Whatever the class is selected in step-2, it must implements java.io.serializable. Hence step-2 class is known as serializable sub class. 4. Choose the set of data members in every serializable sub class. 5. Define set of setXxx(-) for each and every serializable sub class. 6. Define set of getXxx() for each and every serializable sub class. 7. Whatever the serializable sub class we are passing in the package the class name must be given as file name with an extension of .java P) Write a serializable sub class for representing student information. package stupack; import java.io.Serializable; public class stupack implements Serializable {
62

K.V.R Sir 11am JSE int stno; String name; float marks; public void setStno(int stno) { this.stno=stno;

} public void setName(String name) { this.name=name; } public void setMarks(float marks) { this.marks=marks; } public int getStno() { return stno;

} public String getName() { return name;

63

K.V.R Sir 11am JSE } public float getMarks() { return marks; } } Development of Serialization Process: 1. Create an Object of Serializable sub class EX: Student so=new Student()
0

stno name

so
xxx

Null

0.0

marks

2. Set the values for Datamembers of serializable sub class Object by using setXxx(-) EX: so.setStno(10); so.setName(sathya); so.setMarks(99.99f);

stno name

so
xxx

Null

0.0

marks

64

K.V.R Sir 11am JSE

Here so resides in heap memory(as a part of main memory) 3. Choose the file name and open it into write mode with the help of FileOutputStream class. Student.data fos

xxx

4. Creae an Object of java.io.ObjectOutputStream class because an Object of FileOutputStream is unable to write the entire content of serializable sub class object. a. ObjectOutputStream(FileOutputStream) b. Public void writeObject(Object) ObjectOutputStream oos=new ObjectOutputStream(fos); Here oos and fos are called child/sequential streams () child/subsequent Streams: If one stream Object is pointing to another stream Object and both the Stream objects to same type such stream Objects are known as child/subsequent Streams. Sm(HDD) (fos)
Student.data

oos

fis

65

K.V.R Sir 11am JSE

5. Write/transfer the entire content of the serializable object into the file of secondary memory. EX: oos.writeObject(so); Sm(HDD) (fos)
Student.data

oos

fis

10 Siva 99.99

6. Close or terminate the file which is opened in write mode. EX: oos.close() fos.close() P) Write a Java program which illustrates the concept of Serialization (save a record in Stupack file). import java.io.*; import stupack.stupack; class serial { public static void main(String args[]) { try
66

K.V.R Sir 11am JSE { //step-1 stupack so=new stupack(); java.util.Scanner s=new java.util.Scanner(System.in); //Step-2 System.out.println("Enter student number"); int sno=Integer.parseInt(s.nextLine()); System.out.println("Enter student name"); String name=s.nextLine(); System.out.println("Enter student marks"); float marks=Float.parseFloat(s.nextLine()); //step-3 System.out.println("Enter file name to write student data to a file"); String fname=s.nextLine(); FileOutputStream fos=new FileOutputStream(fname); //step-4 ObjectOutputStream oos=new ObjectOutputStream(fos); //step-5 oos.writeObject(so); System.out.println("Student data has writen into a file sucessfully"); //step-6 oos.close(); fos.close(); }

67

K.V.R Sir 11am JSE catch(IOException ie) { System.err.println("Unable to open the file in write mode"); } catch(Exception e) { System.err.println(e); } }

/*OUTPUT Enter student number 11 Enter student name Bhargav Enter student marks 99.99 Enter file name to write student data to a file progress Student data has writen into a file sucessfully

*/

68

K.V.R Sir 11am JSE Phase-III: Development of de-serialization process 1. Create an Object of Serializable sub class for holding de-serialized data. EX: Student so=new Student();

stno name

so
xxx

Null

0.0

marks

2. Choose the file name and open it into read mode with the help of FileInputStream class. Student.data fis
10 Sathya 99.99

3. Create an Object of java.io.Serializable because an Obejct of FileInputStream class is unable to read the entire record of a file. Java.io.ObjectInputStream a. ObjectInputStream(FileInputStream) b. Public Object readObject()

Sm(HDD) (fos)
Student.data fis 69

K.V.R Sir 11am JSE N ois


10 Siva 99.99 10 Sathya 99.99

V I R O NMENT

child/subsequent Streams:

EX: ObjectInputStream ois=new ObjectInputStream(fos); 4. Read or Transfer the entire record of a file EX: Object obj=ois.record.Object()

100

Sathya

99.99

De-serialized Data

5. Type cast an Object of java.lang.Object into serializablesub class Object. So=(Student)obj; 6. Obtain de-serialized data by applying set of getXxx methods. EX: System.out.println(Student no=+so.getStno()); 7. Close or terminate the file which is opened in Read mode. EX: ois.close() Fis.close() P) Write a Java program which illustrates the concept of de-serialization retrieve record of a Student file. import java.io.*;

70

K.V.R Sir 11am JSE import stupack.stupack; class deserial { public static void main(String args[]) { try { //step-1 stupack so=new stupack(); //step-2 DataInputStream dis=new DataInputStream(System.in); System.out.println("enter the file name to read stupack data"); String fname=dis.readLine(); FileInputStream fis=new FileInputStream(fname); //step-3 ObjectInputStream ois=new ObjectInputStream(fis); //step-4 Object obj=ois.readObject(); //step-5 so=(stupack)obj; //step-6 System.out.println("student number="+so.getStno()); System.out.println("student name="+so.getName()); System.out.println("student marks="+so.getMarks());

71

K.V.R Sir 11am JSE //step-7 ois.close(); fis.close(); } catch(IOException ie) { System.err.println("Unable to open the file in write mode"); } catch(Exception e) { System.err.println(e); } }

/*OUTPUT C:\>java deserial enter the file name to read stupack data progress student number=0 student name=null student marks=0.0 */

72

K.V.R Sir 11am JSE Types of Serializations: Serialization types are divided into four types they are 1) 2) 3) 4) Complete Serialization Selective Serialization Automatic Serialization Manual Serialization

1) Complete Serialization: A complete serialization is one in which all the datamembers of Serializable sub class participate in serialization. EX: package stupack; import java.io.Serializable; public class stupack implements Serializable { int stno; String name; float marks; public void setStno(int stno) { this.stno=stno;

} public void setName(String name) { this.name=name; } public void setMarks(float marks) {


73

K.V.R Sir 11am JSE this.marks=marks; } public int getStno() { return stno;

} public String getName() { return name; } public float getMarks() { return marks; } } 2) Selective Serialization: A selective serialization one in which few datamembers of serializable sub class participates in serialization process. Programmatically if we dont want to make any datamember of serializable sub class participate in serialization then that data member declaration must preceded by a keyword transient. Hence transient variables of serializable sub class never participates in serialization process. EX: class student implement java.io.serializable { transient int sno; String sname; Float marks;
74

K.V.R Sir 11am JSE ---------------------------------------------------------} Hence an Object of Student class participates in selective serialization complete and selective serializations with datamembers of serializable subclass. 3) Manual Serialization: If any user defined class of Java explicitly implementing java.io.serializable interface then an Object of user defined class participates in manual serialization or a manual serialization is one in which a class of Java explicitly implements java.io.serializable. EX: class Accoutn implements java.io.serializable //explicit implementation { ------------------} Hence Account class object participates in manual serialization. Automatic serialization: If any user defined class of Java explicitly extends serializable sub class then the object of user defined sub class participates in automatic serialization. Def: Each and every sub class of serializable sub class participates in serialization process known as Automatic serialization. EX: class SavingsAccoutn extends Account { -------------------------}

75

K.V.R Sir 11am JSE Character Streams: Character Streams are those which will transfer two bytes at a time between primary memory and secondary memory. Character Streams are more effective than byte streams because data transfer rate of Character streams is more compared to byte streams. Character Streams are containing two categories of classes they are a) Some of the classes of Character streams transfers two bytes at a time from primary memory to secondary memory(Write operation related class) b) Some other classes of Character streams transfer two bytes at a time from secondary memory to primary memory(read operation related classes) all byte and character streams related classes are present in a predefined package called java.io.*;

3 1 InputStream Reader FileReader

R
1

E A

Object

D W
2 4

R I T E
6 Write OutputStream FileWriter

76

K.V.R Sir 11am JSE

The classes 1,2,3,4 are predefined abstract classes present in java.io.* package reserved by SUN Microsystem for future innovations in file programming and whose direct usage is not there in real world applications. The classes 5 and 6 are the bottom most concrete sub classes and whose direct usage will be there in real world applications provided the programmer is interested in achieving data persistency through files concept. The functionality of file reader of Character Streams is equivalent to FileInputStream of Byte Streams but an Object of file reader reads two bytes and an object of FileInputStream reads one byte. The functionality of Filewriter of Character Streams is equivalent to FileOutputStream of byte stream but an object of FileWriter writes two bytes an an Object of FileOutputStream writes one byte. Write a Program on FileWriter. import java.io.*; class DataWrite { public static void main(String args[]) { try { //step-1 String fname=args[0]; //step-2 FileWriter fw=new FileWriter(fname,true); //step-3 for(int i=1;i<=10;i++) { fw.write(i);
77

K.V.R Sir 11am JSE } System.out.println("data written to the fos"); fw.close(); } catch(IOException ie) { System.err.println("unable to Open file"); } catch(ArrayIndexOutOfBoundsException ae) { System.err.println("Please enter file name"); } catch(Exception e) { System.err.println(e); } } } Write a program on FileReader. import java.io.*; class Dataread { public static void main(String args[]) {

78

K.V.R Sir 11am JSE try { //step-1 String fname=args[0]; //step-2 FileReader fr=new FileReader(fname); //step-3 int i; while((i=fis.read())!=-1) { System.out.println(i); }

System.out.println("data written to the fos"); fis.close(); } catch(IOException ie) { System.err.println("unable to Open file"); } catch(ArrayIndexOutOfBoundsException ae) { System.err.println("Please enter file name"); }

79

K.V.R Sir 11am JSE catch(Exception e) { System.err.println(e); } } } Network programming: Network programming is one of the distinct feature facility available in Java programming. The aim of network programming is to store the data among multiple machines which are located either in same network and different network. Def: A network is collection of inter connected autonomous/ non autonomous computers connected with server. While we are developing network based programming related applications, we are writing two types of programs they are 1. Client side program 2. Server side program In otherwords with the concepts of network we can also develop client/server side applications I includes the above two programs Client: A client is a Java program which always makes a request to the server to get the services form Server. Server: A server is also a program in Java which receives the client request process the client request and gives response back to client. Conclusion: In order to develop network based applications we need to import java.net.*(Main package) and java.io.*(dependent package). DNS(Domain Naming Service): It is one of the physical name of the computer where server side program resides. The default DNS of every PC is Localhost IP Address. Localhost IP Address: It is one of four parts numerical address of physical machine where the server side program resides. The default IP address of every PC is 127.0.0.1.This address is known as Loop back Address. Port Number: It is one of the logical numerical ID where server side program is running. Hence if we want to establish the conversational state between client and server side applications, first we must establish communication channel or bridge between client and server side applications by passing (DNS/IP address, Port No). Let us consider the following diagram establish the
80

K.V.R Sir 11am JSE conversational state between client and server side program is nothing but performing cycle of read and write operations or output Streams and input Streams or DataOutputStream and DataInputStream. M1
DOS OS W R IS DIS

M2

req
Client Program

res

Server side Program

DIS IS R

W OS DOS

DOS-DataOutPutStream OS-OutputStream W-Write R-Read IS-InputStream DIS-DataInputStream Steps or guidelines for developing server side program: 1. 2. 3. 4. Write a server side program. Each and every server side program must run at certain or distinct port number. Serverside program accepts client request. (III) Serverside program reads request parameters obtaining an Object of InputStream and pass it to DataInputStream. (IV) 5. Server side program must contain business logic for request processing. (V) 6. Serverside program give response back to the client by obtaining an object OutputStream and pass it to DataOutputStream. (VI) 7. Serverside program closes the client request(optional). Steps/ Guidelines for development of Client Side Program: 1. Write Clientside program

81

K.V.R Sir 11am JSE 2. Each and every client side program must obtain the connection from server side program by passing(DNS/IP address, Port Number) (I) 3. Client side program makes a request to server side program by obtaining an object of OutputStream and pass it to DataOutputStream. (II) 4. Each and every Clientside program must receive server side program response by obtaining an object of InputStream and pass it to DataInputStream. (VII) 5. Display the result of Server side program at the client side on the client console. (VIII) 6. Clientside program closes it request by itself (optional). Hence I,II,III, ------,VIII are used for global steps establishing conversational state between client and Serverside programs.

82

K.V.R Sir 11am JSE

83

You might also like