70
What is final in Java? Final variable , Method and Class Example Final in java is very important keyword and can be applied to class, method, and variables in Java. In this java final tutorial we will see what is final keyword in Java, what does it mean by making final variable, final method and final class in java and what are primary benefits of using final keywords in Java and finally some examples of final in Java. Final is often used along with static keyword in Java to make static final constant and you will see how final in Java can increase performance of Java application. Example of Final variable, Final method and Class in Java What is final keyword in Java? Final is a keyword or reserved word in java and can be applied to member variables, methods, class and local variables in Java. Once you make a reference final you are not allowed to change that reference and compiler will verify this and raise compilation error if you try to re-initialized final variables in java. What is final variable in Java? Any variable either member variable or local variable (declared inside method or block) modified by final keyword is called final variable. Final variables are often declare with static keyword in java and treated as constant. Here is an example of final variable in Java public static final String LOAN = "loan"; LOAN = new String("loan") //invalid compilation error Final variables are by default read-only. What is final method in Java Final keyword in java can also be applied to methods. A java method with final keyword is called final method and it can not be overridden in sub-class. You should make a method final in java if you think it’s complete and its behavior should remain constant in sub-classes. Final methods are faster than non-final methods because they are not required to be resolved during run-time and they are bonded on compile time. Here is an example of final method in Java: class PersonalLoan{ public final String getName(){ return "personal loan"; }

CoreJavaIneterviews&Answers

  • Upload
    phani

  • View
    7

  • Download
    0

Embed Size (px)

DESCRIPTION

interview

Citation preview

What is final in Java? Final variable , Method and Class ExampleFinal in java is very important keyword and can be applied to class, method, and variables in Java. Inthis java final tutorial we will see what is final keyword in Java, what does it mean by making final variable, final method and final class in java and what are primary benefits of using final keywords in Java and finally some examples of final in Java. Final is often used along with static keyword in Java tomake static final constant and you will see how final in Java can increase performance of Java application.Example of Final variable, Final method and Class in JavaWhat is final keyword in Java?Final is a keyword or reserved word in java and can be applied to member variables, methods, class and local variables in Java. Once you make a reference final you are not allowed to change that reference and compiler will verify this and raise compilation error if you try to reinitiali!ed final variables in java.What is final variable in Java?"ny variable either member variable or local variable #declared inside method or block$ modified by final keyword is called final variable. Final variables are often declare with static keyword in java and treated as constant. %ere is an example of final variable in Javapublic static final String LOAN = "loan";LOAN = new String("loan") //invalid compilation errorFinal variables are by default readonly.What is final method in JavaFinal keyword in java can also be applied to methods. " java method with final keyword is called final method and it can not be overridden in subclass. &ou should make a method final in java if you think it's complete and its behavior should remain constant in subclasses. Final methods are faster than nonfinal methods because they are not re(uired to be resolved during runtime and they are bonded on compile time. %ere is an example of final method in Java:class PersonalLoan{ public final String getName(){ return "personal loan"; }}class CheapPersonalLoan extens PersonalLoan{!O"erriepublic final String getName(){return "c#eap personal loan"; //compilation error: overridden method is final}}What is final Class in JavaJava class with final modifier is called final class in Java. Final class is complete in nature and can not be subclassed or inherited. )everal classes in Java are final e.g. )tring, Integer and other wrapper classes. %ere is an example of final class in javafinal class PersonalLoan{}class CheapPersonalLoan extens PersonalLoan{$$compilation error% cannot in#erit from final class }Benefits of final keyword in Java%ere are few benefits or advantage of using final keyword in Java*+. Final keyword improves performance. ,ot just J-. can cache final variable but also application can cache fre(uently use final variables./. Final variables are safe to share in multithreading environment without additional synchroni!ation overhead.0. Final keyword allows J-. to optimi!ed method, variable or class.Final and Immtable Class in JavaFinal keyword helps to write immutable class. Immutable classes are the one which can not be modified once it gets created and )tring is primary example of immutable and final class which I have discussed in detail on 1hy )tring is final or immutable in Java. Immutable classes offer several benefits one of them is that they are effectively readonly and can be safely shared in between multiple threads without any synchroni!ation overhead. &ou can not make a class immutable without making it final and hence final keyword is re(uired to make a class immutable in java.Example of Final in JavaJava has several system classes in J23 which are final, some example of final classes are )tring, Integer, 2ouble and other wrapper classes. &ou can also use final keyword to make your code better whenever it re(uired. )ee relevant section of java final tutorial for example of final variable, final method and final class in Java.Important points on final in Java+. Final keyword can be applied to member variable, local variable, method or class in Java./. Final member variable must be initiali!ed at the time of declaration or inside constructor, failure to do so will result in compilation error.0. &ou can not reassign value to final variable in Java.4. Local final variable must be initiali!ing during declaration.5. Only final variable is accessible inside anonymous class in Java.6. Final method can not be overridden in Java.7. Final class can not be inheritable in Java.8. Final is different than finally keyword which is used on 9xception handling in Java.:. Final should not be confused with finali!e#$ method which is declared in object class and called before an object is garbage collected by J-..+;. "ll variable declared inside java interface are implicitly final.++. Final and abstract are two opposite keyword and a final class can not be abstract in java.+/. Final methods are bonded during compile time also called static binding.+0. Final variables which is not initiali!ed during declaration are called blank final variable and must beinitiali!ed on all constructor either explicitly or by calling this#$. Failure to do so compiler will complain as t implement Comparable than while putting them into Sorte4ap& always provided corresponding 0omparator which can provide sorting logic.2+ 6rder of comparison is very important while implementing 0omparable or 0omparator interface. for e(ample if you are sorting object based upon name than you can compare first name or last name on any order& so decide it judiciously. " have shared more detailed tips on compare.o on my post how to implement CompareTo in Java.4+ Comparator has a distinct advantage of being self descriptivefor e(ample if you are writing Comparator to compare two =mployees based upon there salary than name that comparator as Salar&0omparator& on the other hand compareTo1+#ifferen$e between %rray&ist and 'e$tor in JavaArra&List and *ector are two of most used class on java collection package and difference between @ector and #rray%ist is one of the most frequently asked java interview question on first round or phone interview. Though it$s quite a simple question in my opinion but knowledge of when to use @ector over #rray%ist or does matter if you are working on a project. "n this article we will some point based difference between Vector and rra!"ist in Java and trying to understand the concept behind those differences. Altimate goal is to familiari-e yourself with distinguish property of Arra&List and *ector. ?y the way Java 4 adds another implementation of List interface which is similar to @ector and#rray%ist but provides better concurrency access than @ector& its called Copy6n.rite#rray%ist. ?y the way this is the third article on discussing about Collection interview question&Difference between %inked%ist and #rray%ist and %ist vs 'et are other popular interview questions based upon collection framework in Java.?efore seeing differences between Vector and rra!"ist& let>s see some similarities between these two and why we can use #rray%ist in place of @ector on certain scenario.*+ *ector and Arra&List are inde( based and backed up by an array internally.,+ ?oth #rray%ist and @ector maintains the insertion order of element. 7eans you can assume that you will get the object in the order you have inserted if you iterate over #rray%ist or @ector./+ ?oth "terator and %ist"terator returned by ArrayList and Vector are failBfast.2+ Arra&List and *ector also allows null and duplicates.Vector vs rra!"ist in Java8ow let>s see some key difference between *ector and Arra&List in Java, this will decide when is the right time to use @ector over #rray%ist and viceBversa. Differences are based upon properties like synchroni-ation& thread safety& speed& performance & navigation and "teration over %ist etc.#$ S!nchroni%ation and thread&safet!:irst and foremost difference between @ector and #rray%ist is that Vector is s!nchroni%ed and #rray%ist is not& what it means is that all the method which structurally modifies @ector e.g. add 1+ or remove 1+ are synchroni-ed which makes it threadBsafe and allows it to be used safely in a multiBthreaded and concurrent environment. 6n the other hand #rray%ist methods are not synchroni-ed thus not suitable for use in multiBthreaded environment. This is also a popular interview question on thread& where people ask why #rray%ist can not be shared between multiple threads.'$ Speed and (erformanceArra&List is way faster than *ector) 'ince @ector is synchroni-ed and threadBsafe it pays price of synchroni-ation which makes it little slow. 6n the other hand Arra&List is not synchroni-ed and fast which makes it obvious choice in a singleBthreaded access environment. s o bac& to 3inleton pattern in Java and see double chec&ed loc&in in 3inleton with +olatile and without volatile &e#word in 1ava"$77 7 >a"a program to emonstrate w#ere to use *olatile ?e&wor in >a"a' 7 ,n t#is example Singleton ,nstance is eclare as "olatile "ariable to ensure 7 e"er& t#rea see upate "alue for 6instance' 7 7 !aut#or >a"in 5aul 7$public class Singleton{private static volatile Singleton 6instance; $$"olatile "ariable public static Singleton getInstance(){ if(6instance == null){synchronized(Singleton'class){if(6instance == null)6instance = new Singleton();} } return 6instance;}-f #ou loo& at the code carefull# #ou will be able to fiure out246 We are onl# creatin instance one time76 We are creatin instance la$il# at the time of first re)uest comes"-f we do not ma&e 6instance variable volatile then Thread which is creatin instance of 3inleton is not able to communicate other thread, that instance has beencreated until it comes out of the 3inleton bloc&, so if Thread % is creatin 3inleton instance and 1ust after creation lost the C,=, all other thread will not be able to see value of 6instance as not null and the# will believe its still null"Wh#? because reader threads are not doin an# loc&in and until writer thread comes out of s#nchroni$ed bloc&, memor# will not be s#nchroni$ed and value of 6instance will not be updated in main memor#" With +olatile &e#word in Java this is handled b# Java himself and such updates will be visible b# all reader threads"3o in 3ummar# apart from s#nchroni$ed &e#word in Java, volatile &e#word is also usedto communicate content of memor# between threads"&et+s see another example of volatile keyword in Javamost of the time while writin ame we use a variable b+xit to chec& whether user has pressed exit button or not, value of this variable is updated in event thread and chec&ed in ame thread , 3o if we don't use volatile &e#word with this variable , a"in 5aul 7$public class 0ount-ownLatc#-emo {public static void main(String argsBC) { final Count(ownLatch latc# = new Count(ownLatch(D); *hread cac#eSer"ice = new *hread(new Ser"ice("0ac#eSer"ice"2 1EEE2 latc#)); *hread alertSer"ice = new *hread(new Ser"ice("AlertSer"ice"2 1EEE2 latc#)); *hread "aliationSer"ice = new *hread(new Ser"ice("*aliationSer"ice"2 1EEE2 latc#));

cac#eSer"ice'start(); $$separate t#rea will initiali8e 0ac#eSer"ice alertSer"ice'start(); $$anot#er t#rea for AlertSer"ice initiali8ation "aliationSer"ice'start();

// application should not start processing any thread until all service is up // and ready to do there job. // Countdown latch is idle choice here, main thread will start with count // and wait until count reaches !ero. each thread once up and read will do // a count down. this will ensure that main thread is not started processing // until all services is up.

//count issince we have"hreads #$ervices%

try{latc#'await();$$main t#rea is waiting on 0ount-ownLatc# to finis#System'out'println("All ser"ices are up2 Application is starting now"); }catch(Interrupted+,ception ie){ ie'printStac?.race(); }

}

}$77 7 Ser"ice class w#ic# will be execute b& .#rea using 0ount-ownLatc# s&nc#roni8er' 7$class Ser"ice implements -unnable{private final String name;private final int time.oStart;private final Count(ownLatch latc#;

public Ser"ice(String name2 int time.oStart2 Count(ownLatch latc#){this'name = name;this'time.oStart = time.oStart;this'latc# = latc#;}

!.verridepublic void run() {try {*hread'sleep(time.oStart);} catch (Interrupted+,ception ex) {Logger'getLogger(Ser"ice'class'getName())'log(Level'S+*+s time to see e(ample of Cyclic?arrier in Java. ere is a simple e(ample of 0&clic;arrier in Java on which we initiali-e 0&clic;arrier with / parties& means in order tocross barrier& / thread needs to call await() method. each thread calls await method in short duration but they don>tproceed until all / threads reached barrier& once all thread reach barrier& barrier gets broker and each thread started there e(ecution from that point. "ts much clear with the output of following e(ample of 0&clic;arrier in Java)import /a"a'util'concurrent';ro?en;arrier+xception;import /a"a'util'concurrent'0&clic;arrier;import /a"a'util'logging'Le"el;import /a"a'util'logging'Logger;$77 7 >a"a program to emonstrate #ow to use 0&clic;arrier in >a"a' 0&clic;arrier is a 7 new 0oncurrenc& @tilit& ae in >a"a G 0oncurrent pac?age' 7 7 !aut#or >a"in 5aul 7$public class 0&clic;arrier+xample {//&unnable tas' (or each threadprivate static class .as? implements -unnable {private Cyclic/arrier barrier;public .as?(Cyclic/arrier barrier) {this'barrier = barrier;}!.verridepublic void run() {try {System'out'println(*hread'current.#rea()'getName() F " is waiting on barrier");barrier'await();System'out'println(*hread'current.#rea()'getName() F " #as crosse t#e barrier");} catch (Interrupted+,ception ex) {Logger'getLogger(0&clic;arrier+xample'class'getName())'log(Level'S+*+t know which threads holds lock instead they just know the lock is hold by some thread and they should wait for lock instead of knowing which thread is inside the synchroni-ed block and asking them to release lock. this analogy fits with wait andnotify being on object class rather than thread in Java.These are just my thoughts on wh! wait and notif! method is declared in 3bject class rather than .hread in Java and you have different version than me. "n reality its another design decision made by Java designer like not supporting 6perator overloading in Java. #nyway please post if you have any other convincing reason why wait and notify method should be in Obect class and not on !hread.!ow to avoid deadlo$k in Java *hreadsHow to avoid deadloc& in Java is one of the )uestion which is flavor of the season for multithreadin , as&ed more at a senior level and with lots of follow up )uestions , thouh )uestion loo&s ver# basic but most of developer et stuc& once #ou start oin deep")uestions starts with ;What is deadlo$k ?;answer is simple , when two or more threads waitin for each other to release loc& and et stuc& for infinite time , situation is called deadloc& " it will onl# happen in case of multitas&in"!ow do yo dete$t deadlo$k in Java ?thouh this could have man# answers , m# version is first - would loo& the code if - seenested s#nchroni$ed bloc& or callin one s#nchroni$ed method from other or tr#in to et loc& on different ob1ect then there is ood chance of deadloc& if developer is not ver# careful"other wa# is to find it when #ou actuall# et loc&ed while runnin the application , tr#to ta&e thread dump , in *inux #ou can do this b# command ;&ill !:; , this will print status of all the thread in application lo file and #ou can see which thread is loc&ed on which ob1ect"other wa# is to use 1console , 1console will show #ou exactl# which threads are et loc&ed and on which ob1ect"once #ou answer this , the# ma# as& #ou to write $ode whi$h will reslt in deadlo$k ?here is one of m# versionpublic "oi met#o1(){s&nc#roni8e(String'class){S&stem'out'println("AIuire loc? on String'class ob/ect");s&nc#roni8e (,nteger'class) {S&stem'out'println("AIuire loc? on ,nteger'class ob/ect");}}}public "oi met#o3(){s&nc#roni8e(,nteger'class){S&stem'out'println("AIuire loc? on ,nteger'class ob/ect");s&nc#roni8e (String'class) {S&stem'out'println("AIuire loc? on String'class ob/ect");}}}If method+#$ and method/#$ both will be called by two or many threads , there is a good chance of deadlock because if thead + a(uires lock on )ting object while executing method+#$ and thread / ac(uires lock on Integer object while executing method/#$ both willbe waiting for each other to release lock on Integer and )tring to proceed further which will never happen.now interviewer comes to final part , one of the most important in my view , !ow to fi" deadlock ? or !ow to avoid deadlock in Java ?if you have looked above code carefully you may have figured out that real reason for deadlock is not multiple threads but the way they access lock , if you provide an ordered access then problem will be resolved , here isthe fixed version.public "oi met#o1(){s&nc#roni8e(,nteger'class){S&stem'out'println("AIuire loc? on ,nteger'class ob/ect");s&nc#roni8e (String'class) {S&stem'out'println("AIuire loc? on String'class ob/ect");}}}public "oi met#o3(){s&nc#roni8e(,nteger'class){S&stem'out'println("AIuire loc? on ,nteger'class ob/ect");s&nc#roni8e (String'class) {S&stem'out'println("AIuire loc? on String'class ob/ect");}}} Jow there would not be an# deadloc& because both method is accessin loc& on -nteer and 3trin ob1ect in same order " so if thread % ac)uires loc& on -nteer ob1ect, thread ( will not proceed until thread % releases -nteer loc& , same wa# thread % will not be bloc&ed even if thread ( holds 3trin loc&because now thread ( will not expect thread % to release -nteer loc& to proceed further"What is -a$e Condition in mltithreadin" 2 4 Examples in Java/ace condition in Java is a type of concurrency bug or issue which is introduced in your program becauseparallel e(ecution of your program by multiple threads at same time, 3ince Java is a multi!threaded prorammin lanuae hence ris& of Aace condition is hiher in Java which demands clear understandin of what causes a race condition and how to avoid that. %n#wa# Gace conditions are just one of ha-ards or risk presented byuse of multiBthreading inJava just like deadlock in Java. /ace conditions occurs when two thread operate on same object without proper synchroni-ation and there operation interleaves on each other. Classical example of -a$e $ondition is incrementing a counter since increment is not an atomic operation and can be further divided into three steps like read& update andwrite. if two threads tries to increment count at same time and if they read same value because of interleaving of readoperation of one thread to update operation of another thread& one count will be lost when one thread overwrite increment done by other thread. atomic operations are not subject to race conditions because those operation cannotbe interleaved. This is also a popular multiBthreading interview questions durin core 1ava interviews" "n this article we will see how to find race condition in Java andtwo sample code patterns which often causes race conditions in Java"%ow to find Bace =onditions in Java4inding /ace conditions in any language is most difficult job and Java is no different& though since readability of Java code is very good and synchroni-ed constructs are well defined heaps to find race conditions by code review. finding race conditions by unit testing is not reliable due to random nature of race conditions. since race conditionssurfaces only some time your unit test may passed without facing any race condition. only sure shot way to find race condition is reviewing code manually or using code review tools which can alert you on potential race conditions based on code pattern and use of synchroni-ation in Java. " solely rely on code review and yet to finda suitable tool for e"posing race condition in ava.Code Example of Aace Condition in Java(ased on my e(perience in Java synchroni-ation and where we use synchroni-ed keyword " found that two code patterns namely 0chec0 and act0 and 0read modif! write0 can suffer race condition if not synchroni-ed properly. both cases rely on natural assumption that a single line of code will be atomic and e(ecute in one shot which is wronge.g. HH is not atomic.5Chec0 and ct5 race condition patternclassical e(ample of 0check and act0 race condition in Java is get,nstance() method of 'ingleton Class& remember that was one questions which we have discussed on *D "nterview questions on 'ingleton pattern in Java as 0ow to write threadBsafe 'ingleton in Java0. get"nstace1+ method first check for whether instance is null and than initiali-ed the instance and return to caller. .hole purpose of 'ingleton is that get"nstance should always return sameinstance of 'ingleton. if you call get,nstance() method from two thread simultaneously its possible that while one thread is initiali-ing singleton after null check& another thread sees value of 9instance reference variable as null 1quitepossible in java+ especially if your object takes longer time to initiali-e and enters into critical section which eventuallyresults in get"nstance1+ returning two separate instance of 'ingleton. This may not happen always because a fraction of delay may result in value of 9instance updated in main memory. here is a code e(amplepublic 'ingleton get"nstance1+Iif19instance JJ null+I KKrace condition if two threads sees 6instance7 null9instance J new 'ingleton1+LMMan easy way to fi( 0chec0 and act0 race conditions is to synchroni-ed keyword and enforce locking which will make this operation atomic and guarantees that block or method will only be e(ecuted by one thread and result of operationwill be visible to all threads once synchroni-ed blocks completed or thread e(ited form synchroni-ed block.read&modif!&update race conditionsThis is another code pattern in Java which cause race condition& classical e(ample is the non thread safe counter we discussed in how to write thread safe class in Java. this is also a very popular multiBthreading question where they ask you to find bugs on concurrent code. readBmodifyBupdate pattern also comes due to improper synchroni-ation of non&atomic operations or combination of two individualatomic operations which is not atomic together e.g. put if absent scenario. consider below codeif1Nhashtable.contains1key++Ihashtable.put1key&value+LMhere we only insert object into hashtable if its not already there. point is both contains1+ and put1+ are atomic but still this code can result in race condition since both operation together is not atomic. consider thread T* checks for conditions and goes inside if block now C3A is switched from T* to thread T, which also checks condition and goes inside if block. now we have two thread inside if block which result in either T* overwriting T, value or viceBversa based on which thread has C3A for e(ecution. "n order to fix this race condition in Java you need to wrap this code inside synchroni-ed block which makes them atomic together because no thread can go inside synchroni-ed block if one thread is already there.These are just some of e"amples of race conditions in Java& there will be numerous based on your business logic and code. best approach to find Gace conditions is code review but its hard because thinking concurrently is not natural and we still assume code to run sequentially. ,roblem can become worse if J@7 reorders code in absent of proper synchroni-ation to gain performance benefit and this usually happens on production under heavily load& whichis worst. " also suggest doing load testing in production like environment which many time helps to e(pose race conditions in java. ,lease share if #ou have faced an# race condition in 1ava pro1ects"5rod$er Consmer #esi"n 5attern with Blo$kin" 6ee Example in Java(roducer Consumer Design pattern is a classic concurrency or threading pattern which reduces coupling between3roducer and Consumer by separating "dentification of work with =(ecution of .ork. "n producer consumer design pattern a shared queue is used to control the flow and this separation allows you to code producer and consumer separately. "t also addresses the issue of different timing require to produce item or consuming item. by using producer consumer pattern both 3roducer and Consumer Thread can work with different speed. "n this articlewe will see What is producer consumer problem which is very popular multiBthreading interview question& ow to solve producer consumer problem using ?locking Eueue and ?enefits of using 3roducer Consumer design pattern. Aeal World Example of ,roducer Consumer Gesin ,attern(roducer consumer pattern is every where in real life and depict coordination and collaboration. %ike one person is preparing food 13roducer+ while other one is serving food 1Consumer+& both will use shared table for putting food plates and taking food plates. 3roducer which is the person preparing food will wait if table is full and Consumer 13erson who is serving food+ will wait if table is empty. table is a shared object here. 6n Java library Executor framewor0 itself implement 3roducer Consumer design pattern be separating responsibility of addition and e(ecution of task. (enefit of ,roducer Consumer ,attern"ts indeed a useful design pattern and used most commonly while writing multiBthreaded or concurrent code. hereis few of its benefit)*+ 3roducer Consumer 3attern simple development. you can Code 3roducer and Consumer independently and Concurrently& they just need to know shared object.,+ 3roducer doesn>t need to know about who is consumer or how many consumers are there. 'ame is true with Consumer./+ 3roducer and Consumer can work with different speed. There is no risk of Consumer consuming halfBbaked item."n fact by monitoring consumer speed one can introduce more consumer for better utili-ation.2+ 'eparating producer and Consumer functionality result in more clean& readable and manageable code. ,roducer Consumer ,roblem in Multi!threadin(roducer&Consumer (roblem is also a popular java interview question where interviewer ask to implement producer consumer design pattern so that 3roducer should wait if Eueue or bucket is full and Consumer should wait if queue orbucket is empty. This problem can be implemented or solved by different ways in Java& classical way is using wait and notify method to communicate between (roducer and Consumer thread and blocking each of them on individual condition like full queue and empty queue. .ith introduction of 8loc0ing9ueue Data 'tructure in Java 4 "tsnow much simpler because ?lockingEueue provides this control implicitly by introducing blocking methods put1+ and take1+. 8ow you don>t require to use wait and notify to communicate between 3roducer and Consumer. ?lockingEueue put1+ method will block if Eueue is full in case of ?ounded Eueue and take1+ will block if Eueue is empty. "n ne(t section we will see a code e"ample of #roducer Consumer design pattern. =sin (loc&in /ueue to implement ,roducer Consumer ,atternBloc$ing%ueue ama-ingly simplifies implementation of 3roducerBConsumer design pattern by providing outofbo( support of blocking on put1+ and take1+. Developer doesn>t need to write confusing and critical piece of waitBnotify code to implement communication. /loc0ing1uue is an interface and Java 4 provides different implantation like Arra&;loc?ingJueue and Lin?e;loc?ingJueue & both implement :":6 order or elements& while Arra&Lin?eJueue is bounded in nature Lin?e;loc?ingJueue is optionally bounded. here is a complete code example of (roducer Consumer pattern with ?lockingEueue. Compare it with classic wait notify code& its much simpler and easy to understand.import java.util.concurrent.?lockingEueueLimport java.util.concurrent.%inked?lockingEueueLimport java.util.logging.%evelLimport java.util.logging.%oggerLpublic class (roducerConsumer(attern Ipublic static void main1'tring argsOP+I

77Creatin" shared ob3e$t ?lockingEueue sharedEueue J new %inked?lockingEueue1+L 77Creatin" 5rod$er and Consmer *hread Thread prodThread J new Thread1new 3roducer1sharedEueue++L Thread consThread J new Thread1new Consumer1sharedEueue++L 77)tartin" prod$er and Consmer thread prodThread.start1+L consThread.start1+LM M775rod$er Class in 3avaclass (roducer implements /unnable Iprivate final 8loc0ing9ueue sharedEueueLpublic 3roducer1?lockingEueue sharedEueue+ Ithis.sharedEueue J sharedEueueLMQ6verridepublic void run1+ Ifor1int iJDL iR*DL iHH+Itry I'ystem.out.println103roduced) 0 H i+LsharedEueue.put1i+LM catch 1"nterrupted=(ception e(+ I%ogger.get%ogger13roducer.class.get8ame1++.log1%evel.'=@=G=& null& e(+LMMMM77Consmer Class in Javaclass Consumer implements GunnableIprivate final ?lockingEueue sharedEueueLpublic Consumer 1?lockingEueue sharedEueue+ Ithis.sharedEueue J sharedEueueLM

Q6verridepublic void run1+ Iwhile1true+Itry I'ystem.out.println10Consumed) 0H sharedEueue.take1++LM catch 1"nterrupted=(ception e(+ I%ogger.get%ogger1Consumer.class.get8ame1++.log1%evel.'=@=G=& null& e(+LMMM

M3utput:3roduced) D3roduced) *Consumed) D3roduced) ,Consumed) *3roduced) /Consumed) ,3roduced) 2Consumed) /3roduced) 4Consumed) 23roduced) 5Consumed) 43roduced) FConsumed) 53roduced) SConsumed) F3roduced) TConsumed) SConsumed) T0ou see 5roucer .#reaprouce number an 0onsumer t#rea consumes it in F-F8 order because bloc&in )ueue allows elements to be accessed in F-F8"That>s all on !ow to se Blo$kin" 6ee to solve 5rod$er Consmer problem or example of 5rod$er $onsmer desi"n pattern" - am sure its much better than wait notif# example but be prepare with both if #ou are oin for an# Java -nterview as -nterview ma# as& #ou both wa#"What is Fa$tory method #esi"n 5attern in Java with Example 0 *torial4actor! design pattern in Java one of the core design pattern which is used heavily not only in JDC but also in various 6pen 'ource framework such as 'pring& 'truts and #pache along with decorator design pattern in Java. :actory Design pattern is based on Encapsulation object oriented concept. :actory method is used to create different object from factory often refereed as "tem and it encapsulate the creation code. 'o instead of having object creation code on client side we encapsulate inside 4actor! method in Java. 6ne of the best e(amples of factory pattern in Java is ;orerKactor& Class of 'wing #3". "n this Design pattern tutorial we will see What is 4actor! method design pattern in Java& .hat are main advantages of factory pattern in Java & Code e(ample of :actory design pattern and .hat problem 4actor! pattern solves in Java or when to use :actory design pattern.This article is in continuation of my design pattern article as *D 663' and '6%"D design principles java programmer should knowand ow to use 6bserver pattern in Java .hat is static factory method or factory design pattern:actory design pattern is used to create objects or Class in Java and it provides loose coupling and high cohesion. :actory pattern encapsulate object creation logic which makes it easy to change it later when you change how object gets created or you can even introduce new object with just change in one class. "n ;6: pattern list :actory pattern is listed as Creation design pattern. :actory should be an interface and clients first either creates factory or get factory which later used to create objects.=(ample of static factory method in JDC ?est =(ample of :actory method design pattern is "alueOf() method which is there in 'tring and wrapper classes like "nteger and ?oolean and used for type conversion i.e. from converting 'tring to "nteger or 'tring to double in java..'ome more e(amples of factory method design pattern from JDC is )"alueOf() method which returns object created by factory equivalent to value of parameter passed.get,nstance() method which creates instance of 'ingleton class.new,nstance() method which is used to create and return new instance from factory method every time called.get.&pe() and new.&pe() equivalent of get,nstance() and new,nstance() factory method but used when factory method resides in separate class.(roblem which is solved b! 4actor! method (attern in Java.henever we talk about object oriented language it will based upon some concept like abstraction& polymorphism etc and on that encapsulationand delegation are important concept any design will becalled good if task are delegated to different object and some kind of encapsulation is there.'ome time our application or framework will not know that what kind of object it has to create at runBtime it knows only the interface or abstract class and as we know we can not create object of interface or abstract class so main problem is frame work knows when it has to create but don$t know what 0ind of object..henever we create object using new() we violate principle of programming for interface rather than implementation which eventually result in infle(ible code and difficult to change in maintenance. ?y using :actory design pattern in Java we get rid of this problem.#nother problem we can face is class needs to contain objects of other classes or class hierarchies within itL this can be very easily achieved by just using the new keyword and the class constructor. The problem with this approach is that it is a very hard coded approach to create objects as this creates dependency between the two classes.'o factor! pattern solve this problem very easily by model an interface for creating an object which at creation time can let its subclasses decide which class to instantiate& :actory 3attern promotes loose coupling by eliminating the need to bind applicationBspecific classes into the code. The factor! methods are typically implemented as virtual methods& so this pattern is also referred to as the Virtual Constructor!. These methods create the objects of the products or target classes.When to use 4actor! design pattern in Java 'tatic :actory methods are common in frameworks where library code needs to create objects of types which may be sub classed by applications using the framework. 'ome or all concrete products can be created in multiple ways& or we want to leave open the option that in the future there may be new ways to create the concrete product. :actory method is used when 3roducts don>t need to know how they are created. .ecan use factory pattern where we have to create an object of any one of subBclasses depending on the data providedCode Example of 4actor! Design (attern in Java:%et$s see an e(ample of how factory pattern is implemented in Code..e have requirement to create multiple currencye.g. "8G& ';D& A'D and code should be e(tensible to accommodate new Currency as well. ere we have made Currency as interface and all currency would be concrete implementation of Currency interface. :actory Class will create Currency based upon country and return concrete implementation which will be stored in interface type. This makes code dynamic and e(tensible.ere is complete code example of 4actor! pattern in Java)interface 0urrenc& { String getS&mbol();}$$ 0oncrete se synchroni!ed keyword in Java and lock the get0ount() method so that only one thread can execute it at a time which removes possibility of coinciding or interleaving./$ use ,tomic 'nte$er, which makes this JJ operation atomic and since atomic operations are thread.safe and saves cost of external synchroni!ation.here is a threadsafe version of =ounter class in Java*GH H hread.)afe 1"ample in Java HGpublic class =ounter I

private int countA"tomicInteger atomic=ount @ new "tomicInteger# ; $A

GH H his method thread.safe now because of lockin$ and synchorni2ation HGpublic synchroni!ed int get=ount#$Ireturn countJJAK

GH H his method is thread.safe because count is incremented atomically HGpublic int get=ount"tomically#$Ireturn atomic=ount.increment"ndLet#$AKK-mportant points about Thread!3afet# in Java%ere is some points worth remembering to write thread safe code in Java, these knowledge also helps you to avoid some serious concurrency issues in Java like race condition or deadlock in Java*+$ Immutable objects are by default threadsafe because there state can not be modified once created. )ince )tring is immutable in Java, its inherently threadsafe./$ Bead only or final variables in Java are also threadsafe in Java.0$ Eocking is one way of achieving threadsafety in Java.4$ )tatic variables if not synchroni!ed properly becomes major cause of threadsafety issues.5$ 9xample of threadsafe class in Java* -ector, %ashtable, =oncurrent%ash.ap, )tring etc.6$ "tomic operations in Java are threadsafe e.g. reading a 0/ bit int from memory because its an atomic operation it canCt interleave with other thread.7$ local "ariables are also t#rea9safe because each thread has there own copy and using localvariables is good way to writing threadsafe code in Java.8$ In order to avoid threadsafety issue minimi!e sharing of objects between multiple thread.:$ -olatile keyword in Java can also be used to instruct thread not to cache variables and read from main memory and can also instruct J-. not to reorder or optimi!e code from threading perspective.?hat's all on how to write thread safe class or code in Java and avoid serious concurrency issues in Java. ?o be frank threadsafety is a little tricky concept to grasp, you need to think concurrently in order to catch whether a code is threadsafe or not. "lso J-. plays a spoiler since it can reorder code for optimi!ation, so the code which looks se(uential and runs fine in development environment not guaranteed to run similarly in production environment because J-. may ergonomically adjust itself as server J-. and perform more optimi!ation and reorder which cause thread.safety issues.!ow to deb" 3ava pro"ram in E$lipse+ebu$$in$ is a must have skill for any java developer. %aving ability to debu$ java pro$ram enables to find you any subtle bug which is not visible during code review or comes when a particular condition offer, ?his becomes even more important if you are working in high fre(uency trading or electronic trading system project where time to fix a bug is very less and bug usually comeson production environment and doesnCt appear in your 1indows MD machine. in my experience debugging java application also helps you understand flow of java program. In this java tutorial we willsee how to debug a java program, setting up remote debugging in java and some java debugging tips on 9clipse and ,etbeans I29. It's also good to know various java debug tool available and how java debugger or jdb works but it's not mandatory for doing debugging in Java. ?o start java debu$$in$ you just needs your project to be configured in a modern I29 like eclipse and ,etbeans and you are ready to debug java program. Java deb""in" toolsI mostly used 9clipse I29 and ,etbeans I29 for java development and these I29 have great support for java debu$$in$. ?hey allow you to set various breakpoints like line breakpoint, conditional breakpoints or exception breakpoint. I prefer 9clipse over netbeans because of its seamless integration with remote debugging because most of the time your applicationwill run on Einux machine and you might not have local version running on your machine, in such scenario remotedebugging is extremely useful. &ou can check how to setup java remote debugging in eclipse for step by step guide on setting remote debugging in eclipses. "part from 9clipse and ,etbeans I29 you can also use Java debugger jdb which is a simple command line based java debugger and based on java platform debugging architecture and can be used to debug java program locally or remotely.Java deb" optionsIf you are not using any &"' for java debugging locally you need to provide java debug option while starting your program. &ou need to provide java debug option also if you are setting up remote debugging session or using jdb for java debugging. Following are the two java debugging option whichneeds to be provided to java program*+ebu$ #ptions &urposeMdebug >sed to run java program in debug modeMrunjdwp*transport@dtNsocket,server@y,suspend@n Eoads in Drocess debugging libraries and specifies the kind of connection to be made.)uspend@y and n is (uite useful for debugging from start or debugging at any point.8sin" 3db to deb" 3ava appli$ation+$ )tart your java program with two options provided above for example, below command will start )tock?rading java program in debug mode. 3 java .4debu$ .4runjdwp:transport5dt6socket,address57888,server5y,suspend5n )tockradin$"fter starting your java application in debug mode you can attach java debugger