You are on page 1of 5

4/7/2016 Top12JavaThread,ConcurrencyandMultithreadingInterviewQuestionsandHowtoAnswersthem|Java67

Java67 SearchThisBlog

JavaProgrammingtutorialsandInterviewQuestions

Home corejava coding thread sql java8 books array string j2ee oop debugging collections datastruc

Categories corejavainterviewquestion
corejava(251)
Top12JavaThread,ConcurrencyandMultithreadingInterview programminginterviewque
programming QuestionsandHowtoAnswersthem SQLinterviewquestions
(182) datastructureinterviewqu
corejava Javaconcurrencyandthreadinterviewquestionsanswers codinginterviewquestions
interview MultithreadingisanimportantfeatureofJavaprogramminglanguage,whichmeansthreadsarealso
questionanswer javacollectioninterviewqu
(72) importantpartofanyJavainterview,infactatbeginnerandfresherlevelThreadinterviewquestionsin javadesignpatternintervie
Javacollection Javaaremostdifficulttoanswer.Onereasonforinterviewquestionrelatedtomultithreadingand questions
tutorial(63) concurrencybeingdifficultisconfusionaroundhowmultiplethreadworkstogetherandsecondis threadinterviewquestions
interview threadsaregenuinelyacomplicatedtopictounderstandandusecorrectly.Mostlythreadinterview strutsinterviewquestions
questions(53)
questionschecksJavaprogrammersknowledgeonJavaThreadAPI,JavaconcurrencyAPI,issues hibernateinterviewquestio
coding(51)
relatedtomultithreadinglikeRaceCondition,threadsafetyanddeadlock.Sometimemultithreading databaseinterviewquestion
CodingProblems
andconcurrencyinterviewquestionalsofocusonparalleldesignpatternrelatedstufflikesolving jdbcinterviewquestions
(31)
producerconsumerproblem,implementingworkstealpatternorsolvingdiningphilosopherproblem serializationinterviewques
Java
programming inJava.Inthisarticle,wewilltakealookatdifferentkindsofmultithreadingandconcurrency arrayinterviewquestions
Tutorial(31) j2eeinterviewquestions
questionsaskedinvariousinterviewse.g.ontelephonicorfacetofaceinterview,onwrittentest,
homework(22)
tobothexperiencedandseniorJavadevelopers,andsometipstoanswerthemcorrectly.Questions stringinterviewquestions
errorand
askedontelephonicorfirstroundofinterviewsaretendtobeeasierandyoumustanswerthemtothe unixinterviewquestions
exception(21)
pointwithkeyword,whichinterviewerisexpecting.Onfacetofaceinterview,bepreparefordifferent miscellaneousinterviewqu
collectiontutorial
example(20) kindsoffollowupquestions. FollowbyEmail

thread(13)
Emailaddress...
J2EE(12)
BooksandResources
SQLinterview JavaInterviewquestionsonConcurrencyandmultithreading
Question(12) BestBooktoLearnJava
AsIsaid,inthisJavaarticle,notonly,Iwillsharesomeofthemost
datastructure Programming
andalgorithm commonlyaskedthreadinterviewquestionatfreshersand
Top3FreeStrutsBooksfor
(12) beginnerslevel,likeupto2to4yearsofexperience,andsometips developers
sql(12) andtrickstoanswerthemcorrectly.Bythewaythesethread 5BookstoImproveYourCo
Java5tutorial interviewquestionsareequallyusefulforseniorJavadevelopersor 10BooksEveryProgramme
(11)
guyswithsomeJavaexperienceinhand.Itriedtoshareanswersof Read
Java8(10)
theseinterviewquestionsonthreadaswellbutIsuggestyoudo 10ComputerAlgorithmBo
javaconcurrency Programmers
someresearchandlearnthetopicwelltoansweranyfollowup
tutorial(10) 10FreeJavaProgramming
JSP(9)
questions,whichcomesduetoyourresponseofthesethread
5BookstoLearnJava8Bet
String(9)
questionsinJava.AnywayherearemycollectionofJavathread
Followers
books(8)
interviewquestionandhowtoanswerstheminJava:
database(8)
Jointhissite
dateandtime(8)
1)Whatisdifferencebetweenstartandrunmethodin withGoogleFriendConnect

threadinterview
JavaThread? Members(881) More
questions(8) Thisthreadinterviewquestionisalsoaskasifstart()method
Java eventuallycallrun()methodthanwhydoyouneedtocall
Multithreading
start()method,whynotcallrun()methoddirectly.wellreasonisthatbecausestartmethodcreates
Tutorial(7)
array(7) anewthreadandcallthecodewritteninsiderunmethodonnewthreadwhilecallingrunmethod
objectoriented executesthatcodeonsamethread.seestartvsrunmethodinJavaformoredetails.
programming(7)
JDBC(4) 2)WritecodetoavoiddeadlockinJavawherenthreadsareaccessingnshared Alreadyamember?Signin
Serialization(4) resources?
RecommendedReading
Unix(4) ThisisaclassicJavamultithreadinginterviewquestions,whichappearsonalmosteverylistofJava
javatips(4) threadquestions.Thisquestionisbasedonriskandissuesfacedbyparallelprogramswithoutproper TheBestBooktoLearnJav
days
Eclipse(3) synchronizationorincorrectsynchronization.Thisquestionexploresconceptoflookingandbest
10JavaWebServiceInterv
JavaScript(3) practicesonacquiringandreleasinglockonsharedresource.Bythewayit'sbeencoveredonmany
Questions
debugging(3) placesaswellandIsuggestreadingHowtopreventdeadlockinJava,notonlyfordetailanswerofthis
Top10AndroidInterviewQ
enum(3) JavamultithreadingquestionbutalsotolearnhowtopreventdeadlockinJava. forJavaProgrammers
javadesign HowtouseanArrayListinJ
pattern(3) 3)WhichoneisbettertoimplementthreadinJava?extendingThreadclassor 10BooksEveryProgramme
Hibernate(2) Read
implementingRunnable?
OOPS(2) 5GreatBookstoLearnJava
WellthisisanotherfrequentlyaskedquestionsonanyJavathreadinterview.Essentiallythesearetwo
WebService(2) BlogArchive
waytoimplementThreadinJavaandbyextendingclassyouareusingyourchancetoextendoneany
bestpractices(2)
onlyoneclassasJavadoesnotsupportmultipleinheritance,byimplementingRunnableinterfaceyou 2016(52)

http://java67.blogspot.in/2012/08/5threadinterviewquestionsanswersin.html 1/5
4/7/2016 Top12JavaThread,ConcurrencyandMultithreadingInterviewQuestionsandHowtoAnswersthem|Java67
designpattern(2) canstillextendanotherclass.SoextendingRunnableorevenCallableisbetterchoice.seeRunnablevs 2015(103)
xml(2) ThreadclassinJavaformoreanswersonthisquestions.Givenit'ssimplicityandfactbasednature, 2014(67)
Excel(1) thisquestionmostlyappearoneithertelephonicroundorinitialscreeningrounds.Keypointsto 2013(44)
JavaCertification mention,whileansweringthisquestionincludes,multipleinheritanceatclasslevelandseparationof
(1) 2012(124)
definingataskandexecutionoftask.Runnableonlyrepresentatask,whileThreadrepresentbothtask
jQuery(1) December(23)
andit'sexecution.
November(8)

4)WhatisBusySpinning?WhyyouwilluseBusySpinningaswaitstrategy? October(26)

ThisisreallyanadvancedconcurrencyinterviewquestionsinJavaandonlyaskedtoexperiencedand September(25)
seniorJavadevelopers,withlotsofconcurrentcodingexperienceunderbelt.Bythewayconceptof August(37)
busyspinningisnotnew,butit'susagewithmulticoreprocessorhasrisenrecently.It'sawait Canweoverloadstaticm
strategy,whereonethreadwaitforaconditiontobecometrue,butinsteadofcallingwaitorsleep JavaProgramEx...

methodandreleasingCPU,itjustspin.Thisisparticularlyusefulifconditionisgoingtobetruequite Canweoverrideprivate
JavaExamplep...
quicklyi.e.inmillisecondormicrosecond.AdvantageofnotreleasingCPUisthat,allcacheddataand
instructionareremainedunaffected,whichmaybelost,hadthisthreadissuspendedononecoreand SpringMVCFramework
QuestionsAnswers
broughtbacktoanotherthread.Ifyoucananswerthisquestion,thatrestassureofagoodimpression.
DifferencebetweenAbst
andEncapsulationi...
5)WhatisdifferencebetweenCountDownLatchandCyclicBarrierinJava?
Canweoverridestaticm
CountDownLatchandCyclicBarrierinJavaaretwoimportantconcurrencyutilitywhichisaddedon JavaMethodHid...
Java5ConcurrencyAPI.Bothareusedtoimplementscenario,whereonethreadhastowaitforother Whatismethodoverridi
threadbeforestartingprocessingbutthereisdifferencebetweenthem.Keypointtomention,while ExampleTutori...
answeringthisquestionisthatCountDownLatchisnotreusableoncecountreachestozero,while Whatismethodoverload
CyclicBarriercanbereusedevenafterbarrierisbroken.Youcanalsoseemypreviousarticledifference JavaExampleTutor.
betweenCyclicBarrierandCountDownLatchinJavaformoredetailedanswerofthisconcurrency DifferencebetweenStrin
StringBufferinJava...
interviewquestionandareallifeexampleofwheretousetheseconcurrencyutilities.
10ThingsEveryJavadev
ShouldKnowaboutP
6)DifferencebetweenwaitandsleepinJava?
WhatisThreadandRun
OnemoreclassicJavamultithreadingquestionfromtelephonicroundofinterviews.Keypointto JavaExample
mentionwhileansweringthisquestionistomentionthatwaitwillreleaselockandmustbecalledfrom
WhatisclassfileinJava
synchronizedcontext,whilesleepwillonlypausethreadforsometimeandkeepthelock.Bytheway, createClassF...
boththrowsIntrupptedExceptionandcanbeinterrupted,whichcanleadtosomefollowup Whatistransientvariabl
questionslike,canweawakeasleepingorwaitingthreadinJava?Youcanalsoreaddetailedansweron Serialization...
mypostofsametitlehere. Whatisvolatilevariable
Whentouse
7)HowdoyousolveproducerconsumerprobleminJava? Howtotraverseiterateo
ArrayListinJava
OneofmyfavoritequestionsduringanyJavamultithreadinginterview,Almosthalfoftheconcurrency
problemscanbecategorizedinproducerconsumerpattern.Therearebasicallytwowaystosolvethis DifferencebetweenHash
HashMapinJava
probleminJava,OnebyusingwaitandnotifymethodandotherbyusingBlockingQueueinJava.
WhatisNoClassDefFoun
lateriseasytoimplementandgoodchoiceifyouarecodinginJava5.Keypointstomention,while Javacauseands...
answeringthisquestionisthreadsafetyandblockingnatureofBlockingQueueandhowthathelps,
5differencebetweenHa
whilewritingconcurrentcode.Youcanalsoexpectlotsoffollowupquestionsincluding,whathappenif andHashMapinJava.
youhavemultipleproducerormultipleconsumer,whatwillhappenifproducerisfasterthanconsumer DifferencebetweenHash
threadorviceversa.Youcanalsoseethislinkforexampleofhowtocodeproducerconsumerdesignin ConcurrentHashMap
Javausingblockingqueue Top12JavaThread,Con
andMultithreadin...
Top10JavaProgrammin
InterviewQuestions...
8)WhyConcurrentHashMapisfasterthanHashtableinJava?
ConcurrentHashMapisintroducedasalternativeofHashtableinJava5,itisfasterbecauseofit's 10AdvancedcoreJavain
questionsforseni...
design.ConcurrentHashMapdivideswholemapintodifferentsegmentsandonlylockaparticular
WhatisPATHandCLAS
segmentduringupdateoperation,insteadofHashtable,whichlockswholeMap.ConcurrentHashMap JavaPathvsClass...
alsoprovideslockfreeread,whichisnotpossibleinHashtable,becauseofthisandlockstriping,
Whatismainmethodin
ConcurrentHashMapisfasterthanHashtable,especiallywhennumberofreaderismorethannumber Whymainispublics..
ofwriters.InordertobetteranswerthispopularJavaconcurrencyinterviewquestions,Isuggest HowtosortArrayListin
readingmypostaboutinternalworkingofConcurrentHashMapinJava. SortingAsc...
Whatisdifferencebetwe
9)Whatisdifferencebetweensubmit()andexecute()methodofExecutorand andsleepinJava?...
ExecutorServiceinJava? DifferencebetweenList
Java
MaindifferencebetweensubmitandexecutemethodfromExecutorServiceinterfaceisthatformer
returnaresultinformofFutureobject,whilelaterdoesn'treturnresult.Bythewaybothareusedto HowJavaachievesplatfo
independence
submittasktothreadpoolinJavabutoneisdefinedinExecutorinterface,whileotherisaddedinto
HowtoMakeCollection
ExecutorServiceinterface.Thismultithreadinginterviewquestionisalsoaskedatfirstroundof ArrayListReadOnlyin
Javainterviews.
Differencebetweenyield
inJava

http://java67.blogspot.in/2012/08/5threadinterviewquestionsanswersin.html 2/5
4/7/2016 Top12JavaThread,ConcurrencyandMultithreadingInterviewQuestionsandHowtoAnswersthem|Java67
10)HowdoyousharedatabetweentwothreadsinJava? Differencebetweenyield
methodinJava
OnemoreJavamultithreadingquestionfromtelephonicroundofinterview.Youcansharedata
betweenthreadbyusingsharedobjectorshareddatastructureslikeQueue.Dependingupon,whatyou HowtoconvertEnumto
JavawithExample...
areusing,youneedtoprovidethreadsafetyguarantee,andonewayofprovidingthreadsafetyisusing
StringtoEnuminJava
synchronizedkeyword.IfyouuseconcurrentcollectionclassesfromJava5e.g.BlockingQueue,you
ConversionExample
caneasilysharedatawithoutbeingbotheredaboutthreadsafetyandinterthreadcommunication.I
HowtofindGCDoftwo
likethisthreadquestion,becauseofit'ssimplicityandeffectiveness.Thisalsoleadsfurtherfollowup inJavaEuclid's...
questionsonissueswhicharisesduetosharingdatabetweenthreadse.g.raceconditions. Differencebetween
CountDownLatchand
CyclicBarrie...
11)WhatisReentrantLockinJava?Haveyouuseditbefore?
ReentrantLockisanalternativeofsynchronizedkeywordinJava,itisintroducedtohandlesomeofthe DifferencebetweenHash
LinkedHashMapinJa
limitationsofsynchronizedkeywords.Manyconcurrencyutilityclassesandconcurrentcollection
DifferencebetweenTree
classesfromJava5,includingConcurrentHashMapusesReentrantLock,toleverageoptimization.
TreeSetinJava
ReentrantLockmostlyusesatomicvariableandfasterCASoperationtoprovidesbetterperformance.
VideoexampleDijkstra
KeypointstomentionisdifferencebetweenReentrantLockandsynchronizedkeywordinJava,which Algorithmshortestpa
includesabilitytoacquirelockinterruptibly,timeoutfeaturewhilewaitingforlocketc.ReentrantLockalsogives
July(5)
optiontocreatefairlockinJava.OnceagainaverygoodJavaconcurrencyinterviewquestionfor
experiencedJavaprogrammers. FeaturedPost

Top10AndroidInterv
12)WhatisReadWriteLockinJava?WhatisbenefitofusingReadWriteLockinJava?
QuestionsAnswersfor
ThisisusuallyafollowupquestionofpreviousJavaconcurrencyquestions.ReadWriteLockisagain
Programmers
baseduponlockstripingbyprovidingseparatelockforreadingandwritingoperations.Ifyouhave
noticedbefore,readingoperationcanbedonewithoutlockingifthereisnowriterandthatcanhugely Howmanyinterviewquestion
improveperformanceofanyapplication.ReadWriteLockleveragethisideaandprovidepoliciesto preparebeforegoingforanyA
Javainterview?notmanyrigh
allowmaximumconcurrencylevel.JavaConcurrencyAPIalsoprovidesanimplementationofthis
article,wewillexplor...
conceptasReentrantReadWriteLock.DependinguponInterviewerandexperienceofcandidate,you
canevenexpecttoprovideyourownimplementationofReadWriteLock,sobeprepareforthataswell.

TheseweresomeofmyfavoriteinterviewquestionsbasedonmultithreadingandconcurrentinJava.
ThreadingandConcurrencyisabigtopicinJavaandhaslotsofinteresting,trickyandtoughquestion
butforstartersandfreshersthesequestionscertainlyhelptoclearanythreadinterviewinJava.AsI
said,mentioningkeypointsareveryimportantwhileansweringquestionsonmultithreadingand
concurrency.Ialsosuggestfurtherreadingonlocking,synchronization,concurrentcollectionsand
concurrencyutilitiesclassestodowellincoreJavaandmultithreadinginterviews.

RelatedJavaInterviewQuestionsandHowtoanswerarticlesformJava67
15TechnicalCoreJavaQuestionsaskedtoExperiencedProgrammeronInterviews
GoodQuestionsonJavaCollectionandConcurrentCollectionwithanswers
Top10JavaDesignPatternQuestionsandHowtoanswerthem
10SpringMVCInterviewQuestionsforJavaProgrammers
10JavaEnumInterviewQuestionsAnswersforbeginners

Advertisement

JavaProgrammingTraining JavaProgrammingClasses

FreeJavaBooks JavaRTF

CoreJava BeginnersJavaCourse

LearnJavaOnline JavaExperts

JavaCertificationCourses MonitoringJava

JavaProjects JavaOnlineCourses

Youmightalsolike:

3Keydifference Howtoconnect Howtofindhighest


betweenmulti EclipsetoOracle repeatingword

http://java67.blogspot.in/2012/08/5threadinterviewquestionsanswersin.html 3/5
4/7/2016 Top12JavaThread,ConcurrencyandMultithreadingInterviewQuestionsandHowtoAnswersthem|Java67
threadingand databaseStepby fromatextFilein...
multitasking? Step...
Linkwithin

PostedbyJavinPaul +98 Recommend this on Google

Labels:corejava,corejavainterviewquestionanswer,javaconcurrencytutorial,programming,thread

5comments:

Anonymous August26,2013at8:30PM
Oneofthegoodquestiononmultithreading,IhaverecentlyfacedinaJavainterview.Afteraskingsome
basic question on thread and synchronization e.g. wait, notify, creating thread, stopping thread, thread
pooletc.Heasked,Howdoyoureducecontentionbetweenthreads?That'sareallygoodquestion.AsIwas
familiar with some techniques of reducing contention among multiple thread, I was quick to bring lock
strippingconcept,whichsplitsalockintomultiplee.g.ReadWritelockhasseparatelockforreadingand
writing.Thiscansignificantlyreducecontention.Anotherwaytoreducethreadcontentionisminimizing
useofsynchronizedkeyword,insteadusingatomicandvolatilevariables.
Reply

AaronFinch August29,2013at8:09PM
Goodquestion.Someanswersarereallygood,especiallywiththebusyspinning.Keepitup.
Reply

Anonymous January25,2014at11:19PM
youranswertospiningisnotcompletelytrue.youcompletlyignorethejavamemorymodelwhichseems
likeanimportandparthere.itonlyguranteesyoutoseethecorrectvalueifaccessedinsyncblock,orsince
1.5withsometypesusingvolatile.butsecondproblemwithnotsynchronizingistheasifserialsemanticof
jvmexecutions.thismightleadyoutosituationswherethereferencetoaobjecthasalreadybeensetbut
theconstructorhasnotbeenrun.soevenwhenyourcheckforref!=nullwillbetrueyoucouldgeterror.
cheers,peter
Reply

AshishThakran July25,2014at1:36AM
Threads can be implemented by extending Thread class, implementing Runnable interface and Callable
interface.

If you want to return an value or throw an exception then use Callable otherwise use Runnable as
extendingThreadclasslimitstheClassinheritanceandalsomakestheprocessheavy.

Belowlinkcanbeusefulifyouwanttofindmore:
DifferentwaystoimplementThreadsinJava
Reply

Kabir December17,2014at1:46AM
Fewmorequestions
Ifyouareaskedtowritecodeforsynchronizingbetweentwothreadsor100threads?whichcodewillbe
hardertowriteandwhy?

Tellmethreeproblemsyouusuallyfaceonconcurrentenvironment.

WhathappendifyouaddtaskintoFixedthreadpoolandworkerqueueisfull?
StumbleUpon
WhathappendifanexceptionisthrowintoaThread?
Reply
Like

Share


Tweet

0

http://java67.blogspot.in/2012/08/5threadinterviewquestionsanswersin.html 4/5
4/7/2016 Top12JavaThread,ConcurrencyandMultithreadingInterviewQuestionsandHowtoAnswersthem|Java67

Enteryourcomment...

Commentas: GoogleAccount

Publish
Preview

NewerPost Home OlderPost

Subscribeto:PostComments(Atom)

PoweredbyBlogger.

http://java67.blogspot.in/2012/08/5threadinterviewquestionsanswersin.html 5/5