QuizFun way to learn more
Ques%onYou’vewri/enanapplica%onforprocessingtasks.Inthisapplica%on,you’veseparatedthecri%calorurgenttasksfromtheonesthatarenotcri%calorurgent.You’veassignedhighprioritytocri%calorurgenttasks.Inthisapplica%on,youfindthatthetasksthatarenotcri%calorurgentaretheonesthatkeepwai%ngforanunusuallylong%me.Sincecri%calorurgenttasksarehighpriority,theyrunmostofthe%me.Whichoneofthefollowingmul%-threadingproblemscorrectlydescribesthissitua%on?A.DeadlockB.Starva1onC.LivelockD.Racecondi1on
AnswerYou’vewri;enanapplica1onforprocessingtasks.Inthisapplica1on,you’veseparatedthecri1calorurgenttasksfromtheonesthatarenotcri1calorurgent.You’veassignedhighprioritytocri1calorurgenttasks.Inthisapplica1on,youfindthatthetasksthatarenotcri1calorurgentaretheonesthatkeepwai1ngforanunusuallylong1me.Sincecri1calorurgenttasksarehighpriority,theyrunmostofthe1me.Whichoneofthefollowingmul1-threadingproblemscorrectlydescribesthissitua1on?A.DeadlockB.Starva%onC.LivelockD.Racecondi1on
Explana%onB.Starva1onThesitua1oninwhichlow-prioritythreadskeepwai1ngforalong1metoacquirethelockandexecutethecodeincri1calsec1onsisknownasstarva1on.
Starva%onStarva&ondescribesasitua1onwhereathreadisunabletogainregularaccesstosharedresourcesandisunabletomakeprogress.Thishappenswhensharedresourcesaremadeunavailableforlongperiodsby"greedy"threads.LivelockAthreadoNenactsinresponsetotheac1onofanotherthread.Iftheotherthread'sac1onisalsoaresponsetotheac1onofanotherthread,thenlivelockmayresult.Aswithdeadlock,livelockedthreadsareunabletomakefurtherprogress.However,thethreadsarenotblocked—theyaresimplytoobusyrespondingtoeachothertoresumework.Thisiscomparabletotwopeoplea;emp1ngtopasseachotherinacorridor:AlphonsemovestohisleNtoletGastonpass,whileGastonmovestohisrighttoletAlphonsepass.Seeingthattheyares1llblockingeachother,Alphonemovestohisright,whileGastonmovestohisleN.They'res1llblockingeachother,so...Source:docs.oracle.com
Ques%on
Whichofthefollowingtwodefini%onsofSync(whencompiledinseparatefiles)willcompilewithouterrors?
A.classSync{publicsynchronizedvoidfoo(){}}B.abstractclassSync{publicsynchronizedvoidfoo(){}}
C.abstractclassSync{publicabstractsynchronizedvoidfoo();}D.interfaceSync{publicsynchronizedvoidfoo();}
Answer
Whichofthefollowingtwodefini%onsofSync(whencompiledinseparatefiles)willcompilewithouterrors?
A.classSync{publicsynchronizedvoidfoo(){}}B.abstractclassSync{publicsynchronizedvoidfoo(){}}
C.abstractclassSync{publicabstractsynchronizedvoidfoo();}D.interfaceSync{publicsynchronizedvoidfoo();}
Explana%onAbstractmethods(inabstractclassesorinterfaces)cannotbedeclaredsynchronized,hencetheop1onsCandDareincorrect.
Ques%onWhichONEofthefollowingop%onscorrectlymakesuseofCallablethatwillcompilewithoutanyerrors?
A.importjava.u1l.concurrent.Callable;classCallableTaskimplementsCallable{publicintcall(){System.out.println("InCallable.call()");return0;}}
B.importjava.u1l.concurrent.Callable;classCallableTaskextendsCallable{publicIntegercall(){System.out.println("InCallable.call()");return0;}}
C.importjava.u1l.concurrent.Callable;classCallableTaskimplementsCallable<Integer>{publicIntegercall(){System.out.println("InCallable.call()");return0;}}
D.importjava.u1l.concurrent.Callable;classCallableTaskimplementsCallable<Integer>{publicvoidcall(Integeri){System.out.println("InCallable.call(i)");}}
AnswerWhichoneofthefollowingop1onscorrectlymakesuseofCallablethatwillcompilewithoutanyerrors?
A.importjava.u1l.concurrent.Callable;classCallableTaskimplementsCallable{publicintcall(){System.out.println("InCallable.call()");return0;}}
B.importjava.u1l.concurrent.Callable;classCallableTaskextendsCallable{publicIntegercall(){System.out.println("InCallable.call()");return0;}}
C.importjava.u%l.concurrent.Callable;classCallableTaskimplementsCallable<Integer>{publicIntegercall(){System.out.println("InCallable.call()");return0;}}
D.importjava.u1l.concurrent.Callable;classCallableTaskimplementsCallable<Integer>{publicvoidcall(Integeri){System.out.println("InCallable.call(i)");}}
Explana%onC.TheCallableinterfaceisdefinedasfollows:publicinterfaceCallable<V>{Vcall()throwsExcep1on;}Inop1onA),thecall()methodhasthereturntypeint,whichisincompa1blewiththereturntypeexpectedforoverridingthecallmethodandsowillnotcompile.Inop1onB),theextendskeywordisused,whichwillresultinacompiler(sinceCallableisaninterface,theimplementskeywordshouldbeused).Inop1onD),thereturntypeofcall()isvoidandthecall()methodalsotakesaparameteroftypeInteger.Hence,themethoddeclaredintheinterfaceIntegercall()remainsunimplementedintheCallableTaskclass,sotheprogramwillnotcompile.
Ques%onHereisaclassnamedPingPongthatextendstheThreadclass.WhichONEofthefollowingPingPongclassimplementa%onscorrectlyprints“ping”fromtheworkerthreadandthenprints“pong”fromthemainthread?
A.publicsta1cvoidmain(String[]args){ThreadpingPong=newPingPong();System.out.print("pong");}}
B.publicsta1cvoidmain(String[]args){ThreadpingPong=newPingPong();pingPong.run();System.out.print("pong");}}
C.publicsta1cvoidmain(String[]args){ThreadpingPong=newPingPong();pingPong.start();System.out.println("pong");}}
D.publicsta1cvoidmain(String[]args)throwsInterruptedExcep1on{ThreadpingPong=newPingPong();pingPong.start();pingPong.join();System.out.println("pong");}}
classPingPongextendsThread{publicvoidrun(){System.out.println("ping");}//ONEOFTHEOPTIONSHERE
AnswerHereisaclassnamedPingPongthatextendstheThreadclass.WhichONEofthefollowingPingPongclassimplementa%onscorrectlyprints“ping”fromtheworkerthreadandthenprints“pong”fromthemainthread?
A.publicsta1cvoidmain(String[]args){ThreadpingPong=newPingPong();System.out.print("pong");}}
B.publicsta1cvoidmain(String[]args){ThreadpingPong=newPingPong();pingPong.run();System.out.print("pong");}}
C.publicsta1cvoidmain(String[]args){ThreadpingPong=newPingPong();pingPong.start();System.out.println("pong");}}
D.publicsta%cvoidmain(String[]args)throwsInterruptedExcep%on{ThreadpingPong=newPingPong();pingPong.start();pingPong.join();System.out.println("pong");}}
classPingPongextendsThread{publicvoidrun(){System.out.println("ping");}//ONEOFTHEOPTIONSHERE
Explana%onD.Themainthreadcreatestheworkerthreadandwaitsforittocomplete(whichprints“ping”).ANerthatitprints“pong”.So,thisimplementa1oncorrectlyprints“pingpong”.Whyaretheotherop1onswrong?A.Themain()methodcreatestheworkerthread,butdoesn’tstartit.So,thecodegiveninthisop1ononlyprints“pong”.B.Theprogramalwaysprints“pingpong”,butitismisleading.Thecodeinthisop1ondirectlycallstherun()methodinsteadofcallingthestart()method.So,thisisasinglethreadedprogram:both“ping”and“pong”areprintedfromthemainthread.C.Themainthreadandtheworkerthreadexecuteindependentlywithoutanycoordina1on.(Notethatitdoesnothaveacalltojoin()inthemainmethod.)So,dependingonwhichthreadisscheduledfirst,youcanget“pingpong”or“pongping”printed.
Ques%onChoosethecorrectop%onbasedonthisprogram:classCOWArrayListTest{publicsta%cvoidmain(String[]args){ArrayList<Integer>aList=
newCopyOnWriteArrayList<Integer>();//LINEAaList.addAll(Arrays.asList(10,20,30,40));System.out.println(aList);}}A.Whenexecutedtheprogramprintsthefollowing:[10,20,30,40].B.Whenexecutedtheprogramprintsthefollowing:CopyOnWriteArrayList.class.C.TheprogramdoesnotcompileandresultsinacompilererrorinlinemarkedwithcommentLINEA.D.Whenexecutedtheprogramthrowsarun1meexcep1onConcurrentModifica1onExcep1on.
AnswerChoosethecorrectop%onbasedonthisprogram:classCOWArrayListTest{publicsta1cvoidmain(String[]args){ArrayList<Integer>aList=
newCopyOnWriteArrayList<Integer>();//LINEAaList.addAll(Arrays.asList(10,20,30,40));System.out.println(aList);}}A.Whenexecutedtheprogramprintsthefollowing:[10,20,30,40].B.Whenexecutedtheprogramprintsthefollowing:CopyOnWriteArrayList.class.C.TheprogramdoesnotcompileandresultsinacompilererrorinlinemarkedwithcommentLINEA.D.Whenexecutedtheprogramthrowsarun1meexcep1onConcurrentModifica1onExcep1on.
Explana%onC.TheprogramdoesnotcompileandresultsinacompilererrorinthelinemarkedwithcommentLINEA.TheclassCopyOnWriteArrayListdoesnotinheritfromArrayList,soana;empttoassignaCopyOnWriteArrayListtoanArrayListreferencewillresultinacompilererror.NotethattheArrayListsuffixintheclassnamedCopyOnWriteArrayListcouldbemisleadingasthesetwoclassesdonotshareanIS-Arela1onship.
Ques%onWhatwillthiscodesegmentprint?
List<Integer>ints=Arrays.asList(1,2,3,4,5);System.out.println(ints.parallelStream().filter(i->(i%2)==0).sequenEal().isParallel());
A.Prints:24B.Prints:falseC.Prints:trueD.Cannotdeterminetheoutputbecausetheprogramhasnon-determinis1cbehaviour
AnswerWhatwillthiscodesegmentprint?
List<Integer>ints=Arrays.asList(1,2,3,4,5);System.out.println(ints.parallelStream().filter(i->(i%2)==0).sequenEal().isParallel());
A.Prints:24B.Prints:falseC.Prints:trueD.Cannotdeterminetheoutputbecausetheprogramhasnon-determinis1cbehaviour
Explana%onB.PrintsfalseThoughthecreatedstreamisaparallelstream,thecalltothesequen1al()methodhasmadethestreamsequen1al.Hence,thecallisParallel()printsfalse.
Ques%onWhichoneofthefollowingmethodsreturnaFutureobject?
A.Theoverloadedreplace()methodsdeclaredintheConcurrentMapinterfaceB.ThenewThread()methoddeclaredintheThreadFactoryinterfaceC.Theoverloadedsubmit()methodsdeclaredintheExecutorServiceinterfaceD.Thecall()methoddeclaredintheCallableinterface
AnswerWhichoneofthefollowingmethodsreturnaFutureobject?
A.Theoverloadedreplace()methodsdeclaredintheConcurrentMapinterfaceB.ThenewThread()methoddeclaredintheThreadFactoryinterfaceC.Theoverloadedsubmit()methodsdeclaredintheExecutorServiceinterfaceD.Thecall()methoddeclaredintheCallableinterface
Explana%onC.Theoverloadedsubmit()methodsdeclaredinExecutorServiceinterface.TheExecutorServiceinterfaceextendstheExecutorinterfaceandprovidesservicessuchastermina1onofthreadsandproduc1onofFutureobjects.Sometasksmaytakeconsiderableexecu1on1metocomplete.So,whenyousubmitatasktotheexecutorservice,yougetaFutureobject.A.Theoverloadedreplace()methodsdeclaredintheConcurrentMapinterfaceremoveanelementfromthemapandreturnthesuccessstatus(aBooleanvalue)ortheremovedvalue.B.ThenewThread()istheonlymethoddeclaredintheThreadFactoryinterfaceanditreturnsaThreadobjectasthereturnvalueD.Thecall()methoddeclaredinCallableinterfacereturnstheresultofthetaskitexecuted.
Ques%onInyourapplica%on,thereisaproducercomponentthatkeepsaddingnewitemstoafixed-sizequeue;theconsumercomponentfetchesitemsfromthatqueue.Ifthequeueisfull,theproducerhastowaitforitemstobefetched;ifthequeueisempty,theconsumerhastowaitforitemstobeadded.Whichoneofthefollowingu%li%esissuitableforsynchronizingthecommonqueueforconcurrentusebyaproducerandconsumer?
A.ForkJoinPoolB.FutureC.SemaphoreD.TimeUnit
AnswerInyourapplica1on,thereisaproducercomponentthatkeepsaddingnewitemstoafixed-sizequeue;theconsumercomponentfetchesitemsfromthatqueue.Ifthequeueisfull,theproducerhastowaitforitemstobefetched;ifthequeueisempty,theconsumerhastowaitforitemstobeadded.Whichoneofthefollowingu1li1esissuitableforsynchronizingthecommonqueueforconcurrentusebyaproducerandconsumer?A.ForkJoinPoolB.FutureC.SemaphoreD.TimeUnit
Explana%onC.SemaphoreTheques1onisaclassicproducer–consumerproblemthatcanbesolvedbyusingsemaphores.Theobjectsofthesynchronizerclassjava.u1l.concurrent.Semaphorecanbeusedtoguardthecommonqueuesothattheproducerandconsumercansynchronizetheiraccesstothequeue.Ofthegivenop1ons,semaphoreistheonlysynchronizer;otherop1onsareunrelatedtoprovidingsynchronizedaccesstoaqueue.A. ForkJoinPoolprovideshelpinrunningaForkJoinTaskinthecontextof
theFork/Joinframework.
B.Futurerepresentstheresultofanasynchronouscomputa1onwhoseresultwillbe“availableinthefutureoncethecomputa1oniscomplete.”D.TimeUnitisanenumera1onthatprovidessupportfordifferent1meunitssuchasmilliseconds,seconds,anddays.
Ques%onWhatwillthiscodesegmentprint?classStringConcatenator{publicsta%cStringresult="";publicsta%cvoidconcatStr(Stringstr){result=result+""+str;}}classStringSplitAndConcatenate{publicsta%cvoidmain(String[]args){Stringwords[]="thequickbrownfoxjumpsoverthelazydog".split("");Arrays.stream(words).parallel().forEach(StringConcatenator::concatStr);System.out.println(StringConcatenator.result);}}
A.overjumpslazydogthebrownfoxquicktheB.thequickbrownfoxjumpsoverthelazydogC.PrintseachwordinnewlineD.Cannotpredictoutput
AnswerWhatwillthiscodesegmentprint?classStringConcatenator{publicsta1cStringresult="";publicsta1cvoidconcatStr(Stringstr){result=result+""+str;}}classStringSplitAndConcatenate{publicsta1cvoidmain(String[]args){Stringwords[]="thequickbrownfoxjumpsoverthelazydog".split("");Arrays.stream(words).parallel().forEach(StringConcatenator::concatStr);System.out.println(StringConcatenator.result);}}
A.overjumpslazydogthebrownfoxquicktheB.thequickbrownfoxjumpsoverthelazydogC.PrintseachwordinnewlineD.Cannotpredictoutput
Explana%onD.CannotpredictoutputWhenthestreamisparallel,thetaskissplitintomul1plesub-tasksanddifferentthreadsexecuteit.ThecallstoforEach(StringConcatenator::concatStr)nowaccessthegloballyaccessiblevariableresultinStringConcatenatorclass.Henceitresultsingarbledoutput.
Ques%onWhatistheexpectedoutputofthiscodesegmentwheninvokedasfollows:java-eaAtomicIntegerTeststa%cAtomicIntegerai=newAtomicInteger(10);publicsta%cvoidmain(String[]args){ai.incrementAndGet();ai.getAndDecrement();ai.compareAndSet(10,11);assert(ai.intValue()%2)==0;System.out.println(ai);}
A.Prints:1011B.Prints:10C.ItcrashesbythrowinganAsser1onErrorD.Prints:9
AnswerWhatistheexpectedoutputofthiscodesegmentwheninvokedasfollows:java-eaAtomicIntegerTeststa%cAtomicIntegerai=newAtomicInteger(10);publicsta%cvoidmain(String[]args){ai.incrementAndGet();ai.getAndDecrement();ai.compareAndSet(10,11);assert(ai.intValue()%2)==0;System.out.println(ai);}
A.Prints:1011B.Prints:10C.ItcrashesbythrowinganAsser%onErrorD.Prints:9
Explana%onC. ItcrashesthrowinganAsser1onError.
Theini1alvalueofAtomicIntegeris10.Itsvalueisincrementedby1aNercallingincrementAndGet().ANerthat,itsvalueisdecrementedby1aNercallinggetAndDecrement().ThemethodcompareAndSet(10,11)checksifthecurrentvalueis10,andifsosetstheatomicintegervariabletovalue11.Sincetheassertstatementchecksiftheatomicintegervalue%2iszero(thatis,checksifitisanevennumber),theassertfailsandtheprogramresultsinanAsser1onError.
Ques%onConsiderthatyouaredevelopingancardsgamewhereapersonstartsthegameandwaitsfortheotherplayerstojoin.Minimum4playersarerequiredtostartthegameandassoonasalltheplayersareavailablethegamehastogetstarted.Fordevelopingsuchkindofgameapplica%onwhichofthefollowingsynchroniza%ontechniquewouldbeideal:A.SemaphoreB.ExchangerC.RunnableD.CyclicBarrier
AnswerConsiderthatyouaredevelopingancardsgamewhereapersonstartsthegameandwaitsfortheotherplayerstojoin.Minimum4playersarerequiredtostartthegameandassoonasalltheplayersareavailablethegamehastogetstarted.Fordevelopingsuchkindofgameapplica%onwhichofthefollowingsynchroniza%ontechniquewouldbeideal:A.SemaphoreB.ExchangerC.RunnableD.CyclicBarrier
Explana%onD.CyclicBarrierCyclicBarrierhelpsprovideasynchroniza1onpointwherethreadsmayneedtowaitatapredefinedexecu1onpointun1lallotherthreadsreachthatpoint.A.ASemaphorecontrolsaccesstosharedresources.AsemaphoremaintainsacountertospecifynumberofresourcesthatthesemaphorecontrolsB.TheExchangerclassismeantforexchangingdatabetweentwothreads.Thisclassisusefulwhentwothreadsneedtosynchronizebetweeneachotherandcon1nuouslyexchangedata.C.Runnableisaninterfaceusedincrea1ngthreads
Ques%onConsiderthefollowingprogramandchoosethecorrectop%ondescribingitsbehaviorclassPingPongextendsThread{publicvoidrun(){System.out.print("ping");thrownewIllegalStateExcep%on();}publicsta%cvoidmain(String[]args)throwsInterruptedExcep%on{ThreadpingPong=newPingPong();pingPong.start();System.out.print("pong");}}A. Thisprogramresultsinacompilererror.B. Printsthepingpongandexcep1oninanyorderC. Thisprogramthrowsarun1meerror.D. Printspongping
AnswerConsiderthefollowingprogramandchoosethecorrectop%ondescribingitsbehaviorclassPingPongextendsThread{publicvoidrun(){System.out.print("ping");thrownewIllegalStateExcep1on();}publicsta1cvoidmain(String[]args)throwsInterruptedExcep1on{ThreadpingPong=newPingPong();pingPong.start();System.out.print("pong");}}A. Thisprogramresultsinacompilererror.B. Printsthepingpongandexcep%oninanyorderC. Thisprogramthrowsarun1meerror.D. Printspongping
Explana%onB.Printsthepingpongandexcep1oninanyorderTheprogramsexecutesfineandtheexactoutputcannotbepredictedasthemainthreadandtheworkerthreadexecuteindependentlywithoutanycoordina1on.
UpcomingWorkshops/Bootcamps
• SOLIDPrinciplesandDesignPa;erns–Aug27th• MicrosoNAzureBootcamp–Aug27th• ModernSoNwareArchitecture–Sep10thPleasevisitCodeOps.techformoredetailssuchasagenda/cost/trainerandregistra1on.
OCPJava:h;p://ocpjava.wordpress.com
Techtalks
q Techtalksareforknowledgesharing-sothereisnocostassociatedwithit
q Weusuallysharethepresenta1on&suppor1ngmaterialtothepar1cipantsaNerthetechtalk
q Dura1onofthetechtalkwouldbefor1hourandwillbegivenatyourofficepremises
q TopicsonwhichweoffertechtalkscanbefoundhereTechTalkTopics
q WealsoofferfreeworkshoponIntroduc1ontoDockerwhichwillbeahands-onsession
Meetups
• Core-Java-Meetup-Bangalore• SoNware-CraNsmanship-Bangalore–20thJuly@Ginserv• Container-Developers-Meetup-20thAug@Avaya• CloudOps-Meetup-Bangalore-20thAug@Avaya• JavaScript-Meetup-Bangalore-20thAug• Technical-Writers-Meetup-Bangalore–25thSep• SoNwareArchitectsBangalore–1stOct@Prowareness• Bangalore-SDN-IoT-NetworkVirtualiza1on-Enthusiasts
[email protected] @GSamarthyamwww.codeops.tech slideshare.net/sgganesh +91 98801 64463 bit.ly/sgganesh
❖ Programming examples are from our book:
❖ Oracle Certified Professional Java SE 8 Programmer Exam 1Z0-809: A Comprehensive OCPJP 8 Certification Guide, S.G. Ganesh, Hari Kiran Kumar, Tushar Sharma, Apress, 2016.
❖ Website: ocpjava.wordpress.com
Meetups
• Core-Java-Meetup-Bangalore• SoNware-CraNsmanship-Bangalore–20thJuly@Ginserv• Container-Developers-Meetup-20thAug@Avaya• CloudOps-Meetup-Bangalore-20thAug@Avaya• JavaScript-Meetup-Bangalore-20thAug• Technical-Writers-Meetup-Bangalore–25thSep• SoNwareArchitectsBangalore–1stOct@Prowareness• Bangalore-SDN-IoT-NetworkVirtualiza1on-Enthusiasts
[email protected] @GSamarthyamwww.codeops.tech slideshare.net/sgganesh +91 98801 64463 bit.ly/sgganesh