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

Java

It is very useful for you
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
25 views

Java

It is very useful for you
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 9
3.10: Thread Synchronization [ Definition: ThreadSynchronation SSS ‘Thread synchronization is the concurrent execution of two or more threads that share critical resources. | When two or more threads need t9 use a shared resource, they need some way to | ensure that the-tesource will betsed by only one thread at a time. The process of | ensuring single thread access toa shared resource ata time is called synchronization. ‘Threads Should be synchronized to avoid critical resource use conflicts. Otherwise, conflicts may arise when parallel-running threads attempt to modify a common variable atthe same time. Y Whyuse Synchronization ‘The synchronization is mainly used to 1. To preventthread interference, 2. Toprevent consistency problem, ¥ ‘Thread Synchronization ‘There are two types of thread synchronization mutual exclusive and inter-thread communication 1. Mutual Exclusive 1. Synchronized method. 2. Synchronized block. (53391 ~ Object Oriented Programming ~Il Sem CSE u DOWNLOADED FROM STUCOR APP Department of CSE. 3, statle synchronization, 2. Cooperation (Inter-thread communication in java) Y Mutual Exclusive Mutual Exclusive helps keep threads from interfering with one another while sharing data, This can be done by two ways in java 1. by synchronized method 2. bysynchronized block ¥ Concept of Lock in Java Synchronization is built around an internal entity known as the lock or monitor. Every object has a lock associated with i. By convention, a thread that needs consistent access to an object's fields has to acquire the object's lock before accessing them, and then release the lock when it's done with them. 1. Javasynchronized method ¥ If you declare any method as synchronized; itis known’ as synchronized method. ‘Synchronized method is used to lock an object for any shared resource. When a thread invokes a synchronized method, it automatically acquires the lock for that object and releases It when the thread completes its task. mtaxtouse: iz ‘Access, modifier synchronized return type method _name(parameters) mel, ‘Example of java synchronized method: class Table{ synchronized void printTable(int n)//synchronized method i for(int it;ke=5il+4) ( systemoutprintin(a); ty Threadsleep(400); catch(Exception ¢){System.outprintin(e); } ) ) } class MyThread1 extends Thread { Table t; MyThread1(Table t){ this.t=t; public void run(){ tprintTable(5); } ae class MyThread2 extends Thread{ Table t; MyThread2(Table t){ this.t=t; } public void runQ{ tprintTable(100); ' d public class TestSynchronization2{ public static void main(String args{]){ Table obj = new Table();_ //only one object MyThread1 tl=new MyThread1(obj); MyThread2 t2=new MyThread2(obj); tLstartQ; t2,startQ; tt Output: 5 10 15 20 25 100 200 300 400 500 2. Synchronized block in java Y Synchronized block can be used to perform synchronization on any specific resource of the method. ¥ Suppose you have 50 lines of code in your method, but you want to synchronize only 5 lines, you can use synchronized block. ¥ Ifyou put all the codes of the method in the synchronized block, it will work same as the synchronized method. Points to remember for Synchronized block + Synchronized block is used to lock an object for any shared resource. + Scope of synchronized block is smaller than the method. Syntax to use synchronized block 1. synchronized (object reference expression) { 2. //code block 3.) Example of synchronized block class Table void printTable(int n) { synchronized(this) //synchronized block { forint i=1;i<=5;i+4){ System.out printin(n*i); try{ Threadsleep(400); _}catch(Exception e){System.out-printin(e);} } } }/fend of the method } class MyThread1 extends Thread{ Table t; MyThread1 (Table t)( this.t=t; } public void run(){ tprintTable(5); } class MyThread2 extends Thread{ Table t; MyThread2(Table t){ thist=t; } public void run(){ tprineTable(100); } } public class TestSynchronizedBlock1 { public static void main(String args{]) { ‘Table obj = new Table();//only one object MyThread1 t1=new MyThread1(obj); MyThread2 t2=new MyThread2(obj); t1.startQ; t2start(}; } } Output: 10 15 20 25 100 200 300 400 500 Definition: Thread A thread is a lightweight sub-process that defines a separate path of execution. It is the smallest unit of processing that can run concurrently with the other parts (other threads) of the same process. Y¥ Threads are independent. v If there occurs exception in one thread, it doesn't affect other threads. v Itusesa shared memory area. os ¥ Asshown inthe above figure, a thread is executed inside the process. v There is context-switching between the threads. Y There can be multiple processes inside the 0S, and one process can have multiple threads. ‘A program can be divided into a number of small processes. Each small process can be addressed asa single thread. [Definition:Mulitheeading Multithreading isa technique of executing moré than one thread, performing different tasks, simultaneously Multithreading enables programs to have more than one execution paths which executes concurrently. Each such execution path fs a thread. For example, one thread is writing content(on a file at the same time another thread Is performing spelling, check. ‘Advantages of Threads/ Multithreading: 1. Threads are light weight compared to processes. 2, Threads share the same address space and therefore can share both data and code. Context switching between threads is usually less expensive that between processes Cost of thread communication fs low than inter-process communication, ‘Threads allow different tasks to be performed concurrently. Reduces the computation time, ‘Through multithreading, efficient utlization of system resources can be achieved, ‘MULTITASKING Multitasking is a process of executing multiple tasks simultane ‘multitasking to maximize the utilization of CPU. sly. We use 53391 ~ Object Oriented Programming ~ Sem CSE 2 DOWNLOADED FROM STUCOR APP Department of CSE. “Multitasking can be achieved in two ways: 1) Process-based Multitasking (Multipracessing):- ‘© It isa feature of executing two or more programs concurrently. ® For example, process-based multitasking enables you to run the Java compiler at the same time that you are using.a text editor or visiting a web site, 2) Thread-based Multitasking (Multithreading):- ‘ It is a feature that a single program can perform two or more tasks simultaneously. “+ For instance, a text editor can format text atthe same time that it is printing, as long.as these two actions are being performed by two separate threads, Differences between mult-threading and multitasking Characteristics Multithreading Multitasking ‘Meaning ‘A process is divided into several | The execution of more than one different sub-processes called as | task simultaneously Is called as threads, which has its own path | mulekasking. of execution. This concept is called as multithreading. Number of CPU | Canbe one or morethanone | One ‘Number of. Various components of the same | One by one jobis being processbeing _| processarebeing executed ata | executed ata time. executed time, Number ofusers | Usually one. More than one, ‘Memory Space | Threads are lighter weight. They | Processes are heavyweight share the same address space | tasks that require their own separate address spaces. ‘Communication | Interthread communication Is | Interprocess communication f= between units | inexpensive ‘expensive and limited Context Switching | Context switching fromone | Context switching from one thread tothe next is lower in| process to another is also costly, What is exception handling? Exception Handling Isa mechanism to handle runtime errors, such as ‘ClassNotFoundException, IOException, SQLException, RemoteException et. by taking the necessary actions, 0 that normal law ofthe aplication ca be maintained. ‘Advantage ofusing Exceptions: Maintains the normal low of execution ofthe application. Exceptions separate error handling cde from regula code ‘Benefit Cleaner lgoethms, less cuter Meaningful Error reporting Exception standardize errr handling JAVA EXCEPTION HANDLING KEYWORDS Exception Handling in java fs managed using the lowing five keywords [SNe] Keyword | Description try | Avlockofzodethatis wie monitored for exception. ~~ Phe catch bloc handles the specie type of exception along catch | with the try block. For each corresponding ty block there exists the catch block Te species the cove that must be executed even Tough exception mayor may not ocr. This keyword is used wo expitiy throw specie exeption Fom the program coe, Te species the exceptions that Gan Be thrown by a parear method ‘nally The java code that might throw an exception i enclosed in try block. It must be used within the method and must be followed by either catch or finally block. €s3381~ Object vented Programing Semester CSE ut DOWNLOADED FROM STUCOR APP Depanmest of CSE © ‘fan exception is generated within the ty black, the remaining statementsin the try bck are not executed > catchBlod: 17 Exceptions thrown during execution of the try black can be caught and handled in a cate block, + On exit from a catch block, normal execution continwes and the fray block is execute. > ‘final Blocks ‘finally block salways executed, regardless ofthe cause of ext rom the ty block oF whether any catch block was executed ¥ Generally finally block is used for freeing resources, cleaning up, closing Even though there fs any exception in the ty block, the statemiénts assured by finally block are sure to execute v Rule: «+ For exch try block there can be zero or more catch blocks, but only one finally block. + The finally block will not be exceuted if program eaits(elther by calling System.ext() or by causing a fatal error that causes the process to abort) ‘The sry-catehSnally structure Senta): wy I) Code beck 1 ‘atch (BecoptonTypet et) 1/Mandle Exception ype exceptions ) ‘atch (BecoptonType2 e2) ( 1/ Handle ExceptionType2 exceptions ) is Analy ( 1/ Codealways executed attr the Jy aa any catch block ) ules for ry. catchand nally Block: 1] Statements that might anerte am exception are placed ina ty block 2} otal statements in thet Slack wl ence the encom i interrupted Man 3) For each ry back there canbe sero ar more catch acs but ony one Ally 4) The uy boc allowed by \oneor more catch Backs 5) Atryboce max befllowodby ether at am one cateh block or on aly lock. 6) cates Bleck species the spe of exception Fe an catch. Ie contin he code ‘known a exception handler 17) Tho catch leks aod al Hock must always appear In conjunction with ary block 4) The order of exception handlers nthe catch block must be fom the mob spec rneramthout Exception handing: (Default excetion handler: slat Spe ‘ pub wat wo maining ors ‘ Inc atass070; Systemovtipringh resto the code.” xcepton In thread mat javalang ArthmetlcEsception/ by aro de ttetenti ot priatd, Program Explanation: ‘The VM frty checks whether the exception is handled oF ot exception is not andes VM provides default exertion ander te performs the following aks Prints ouceacepton desertion. 1 Printsthe stack race (Herarchy of methods where the exception acurred), ia 1 econ Ome je eattne sie econ faerie sample: publics Demo t ube tte void maining ars) ‘ ey in daa 25/0; Systemot pita ) ee Arthmedieicepion) 1 ‘Shmtemautprint(e) p aly ‘Sytemoutprindo( rally back sawayserecuted; ? Systemautprin rest ofthe code"): Arithmetcbxception: / by ero No exceptions thrown: wy co ? CAKENL ron) — , co + hoxtline of the code An exception arises : ext line of the code

You might also like