How to deal with "java.lang.OutOfMemoryError: Java heap ...
文章推薦指數: 80 %
The default max heap size of 64 MB is from before J2SE 5.0. · 2 · The Sun/Oracle JVM has always been quite rigid about specifying the amount memory to use (and ...
Home
Public
Questions
Tags
Users
Companies
Collectives
ExploreCollectives
Teams
StackOverflowforTeams
–Startcollaboratingandsharingorganizationalknowledge.
CreateafreeTeam
WhyTeams?
Teams
CreatefreeTeam
Collectives™onStackOverflow
Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost.
Learnmore
Teams
Q&Aforwork
Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch.
Learnmore
Howtodealwith"java.lang.OutOfMemoryError:Javaheapspace"error?
AskQuestion
Asked
13years,11monthsago
Modified
5monthsago
Viewed
1.9mtimes
523
167
Iamwritingaclient-sideSwingapplication(graphicalfontdesigner)onJava5.Recently,Iamrunningintojava.lang.OutOfMemoryError:JavaheapspaceerrorbecauseIamnotbeingconservativeonmemoryusage.Theusercanopenunlimitednumberoffiles,andtheprogramkeepstheopenedobjectsinthememory.AfteraquickresearchIfoundErgonomicsinthe5.0JavaVirtualMachineandotherssayingonWindowsmachinetheJVMdefaultsmaxheapsizeas64MB.
Giventhissituation,howshouldIdealwiththisconstraint?
Icouldincreasethemaxheapsizeusingcommandlineoptiontojava,butthatwouldrequirefiguringoutavailableRAMandwritingsomelaunchingprogramorscript.Besides,increasingtosomefinitemaxdoesnotultimatelygetridoftheissue.
Icouldrewritesomeofmycodetopersistobjectstofilesystemfrequently(usingdatabaseisthesamething)tofreeupthememory.Itcouldwork,butit'sprobablyalotworktoo.
Ifyoucouldpointmetodetailsofaboveideasorsomealternativeslikeautomaticvirtualmemory,extendingheapsizedynamically,thatwillbegreat.
javajvmout-of-memoryheap-memory
Share
Improvethisquestion
Follow
editedOct24,2020at14:58
BalusC
1.0m363363goldbadges35593559silverbadges35163516bronzebadges
askedSep1,2008at1:10
EugeneYokotaEugeneYokota
93.2k4545goldbadges209209silverbadges313313bronzebadges
4
Thedefaultmaxheapsizeof64MBisfrombeforeJ2SE5.0.ForJ2SE8.0information,see"GarbageCollectorErgonomics"atdocs.oracle.com/javase/8/docs/technotes/guides/vm/….
– AndyThomas
Apr8,2015at15:36
2
IfyoulandedherebecauseeveryOOMquestionisdupedtothisone,makesureyoualsocheckout:stackoverflow.com/questions/299659/…Itprovidesthesolutionforcleaningupmemoryreferences'justintime'beforetheOOM.SoftReferencesmaybethetoolthatsolvesyouractualproblem.
– SteveSteiner
Apr24,2018at20:13
TheSun/OracleJVMhasalwaysbeenquiterigidaboutspecifyingtheamountmemorytouse(andhavingsomeinterestingdefaultsifleftonitsown).ThatwasoneofthenicethingsoftheMicrosoftJVMbackthen-itwasfastanditcouldusewhatevermemorythemachinehad.
– ThorbjørnRavnAndersen
Feb21,2021at16:12
inmycaseImissedgradle.propertiesfiletoaddinmyproject
– MohdQasim
Mar14at7:30
Addacomment
|
30Answers
30
Sortedby:
Resettodefault
Highestscore(default)
Trending(recentvotescountmore)
Datemodified(newestfirst)
Datecreated(oldestfirst)
290
Ultimatelyyoualwayshaveafinitemaxofheaptousenomatterwhatplatformyouarerunningon.InWindows32bitthisisaround2GB(notspecificallyheapbuttotalamountofmemoryperprocess).ItjusthappensthatJavachoosestomakethedefaultsmaller(presumablysothattheprogrammercan'tcreateprogramsthathaverunawaymemoryallocationwithoutrunningintothisproblemandhavingtoexamineexactlywhattheyaredoing).
Sothisgiventhereareseveralapproachesyoucouldtaketoeitherdeterminewhatamountofmemoryyouneedortoreducetheamountofmemoryyouareusing.OnecommonmistakewithgarbagecollectedlanguagessuchasJavaorC#istokeeparoundreferencestoobjectsthatyounolongerareusing,orallocatingmanyobjectswhenyoucouldreusetheminstead.Aslongasobjectshaveareferencetothemtheywillcontinuetouseheapspaceasthegarbagecollectorwillnotdeletethem.
InthiscaseyoucanuseaJavamemoryprofilertodeterminewhatmethodsinyourprogramareallocatinglargenumberofobjectsandthendetermineifthereisawaytomakesuretheyarenolongerreferenced,ortonotallocatetheminthefirstplace.OneoptionwhichIhaveusedinthepastis"JMP"http://www.khelekore.org/jmp/.
Ifyoudeterminethatyouareallocatingtheseobjectsforareasonandyouneedtokeeparoundreferences(dependingonwhatyouaredoingthismightbethecase),youwilljustneedtoincreasethemaxheapsizewhenyoustarttheprogram.However,onceyoudothememoryprofilingandunderstandhowyourobjectsaregettingallocatedyoushouldhaveabetterideaabouthowmuchmemoryyouneed.
Ingeneralifyoucan'tguaranteethatyourprogramwillruninsomefiniteamountofmemory(perhapsdependingoninputsize)youwillalwaysrunintothisproblem.Onlyafterexhaustingallofthiswillyouneedtolookintocachingobjectsouttodisketc.Atthispointyoushouldhaveaverygoodreasontosay"IneedXgbofmemory"forsomethingandyoucan'tworkarounditbyimprovingyouralgorithmsormemoryallocationpatterns.Generallythiswillonlyusuallybethecaseforalgorithmsoperatingonlargedatasets(likeadatabaseorsomescientificanalysisprogram)andthentechniqueslikecachingandmemorymappedIObecomeuseful.
Share
Improvethisanswer
Follow
editedMar23,2019at8:44
Hearen
6,98122goldbadges4848silverbadges5858bronzebadges
answeredSep1,2008at1:29
BenChildsBenChilds
4,28011goldbadge1919silverbadges99bronzebadges
2
9
OpenJDKandOracleJDKhavebundledprofiler-jvisualvm.IfyouwantmoreconveniencesI'dsuggestcommercialYourkit.
– PetrGladkikh
Apr17,2013at4:40
2
Usecloseunusedobjectandarray,sayresultsSet.close();fileOutputStream.close();fileOutputStream.flush();,IuseresultsSet.close()andwasworkingmagically.
– MrSalesi
Sep3,2021at22:35
Addacomment
|
148
RunJavawiththecommand-lineoption-Xmx,whichsetsthemaximumsizeoftheheap.
Seeherefordetails.
Share
Improvethisanswer
Follow
editedMar23,2019at8:51
Hearen
6,98122goldbadges4848silverbadges5858bronzebadges
answeredSep1,2008at5:00
DaveWebbDaveWebb
186k5757goldbadges307307silverbadges298298bronzebadges
2
5
Howtosetthisparameterforever?CauseI'musing'gradlewassemble'command.
– Dr.jacky
Jan19,2017at7:32
3
Run->RunConfigurations->Clickonarguments->insideVMargumentstype-Xms1g-Xmx2g
– ArayanSingh
May24,2018at18:38
Addacomment
|
98
Youcouldspecifyperprojecthowmuchheapspaceyourprojectwants
FollowingisforEclipseHelios/Juno/Kepler:
Rightmouseclickon
RunAs-RunConfiguration-Arguments-VmArguments,
thenaddthis
-Xmx2048m
Share
Improvethisanswer
Follow
editedMar23,2019at8:49
Hearen
6,98122goldbadges4848silverbadges5858bronzebadges
answeredFeb25,2011at18:45
allenhwkimallenhwkim
26.6k1616goldbadges8686silverbadges118118bronzebadges
3
1
hibighostkimandcuongHuyTo,whereis"Arguments"..icanabletoseeuptoRunConfiguration.Pleasetelme.Myneedtodownloadandstorenearly2000contactsfromgmail.Itcrashduetooutofmemoryexception
– AndroidRaji
Nov24,2012at5:49
@AndroiRaji:yourightclickyourmouseontotheJavaclassthathasarunnablemain(thatis"publicstaticvoidmain(String[]args)"),thenchooseRunAs-RunConfiguration.Then"Arguments"isthetabrightaftertheMain(youseethetabsMain,Arguments,JRE,Classpath,Source,Environment,Common).
– CuongHuyTo
Mar4,2014at10:06
Howwoulditbeforintellih?
– Sal-laS
Jul17,2020at6:47
Addacomment
|
69
Increasingtheheapsizeisnota"fix"itisa"plaster",100%temporary.Itwillcrashagaininsomewhereelse.Toavoidtheseissues,writehighperformancecode.
Uselocalvariableswhereverpossible.
Makesureyouselectthecorrectobject(EX:SelectionbetweenString,StringBufferandStringBuilder)
Useagoodcodesystemforyourprogram(EX:UsingstaticvariablesVSnonstaticvariables)
Otherstuffwhichcouldworkonyourcode.
TrytomovewithmultyTHREADING
Share
Improvethisanswer
Follow
editedMar24,2019at6:41
answeredFeb1,2014at5:10
PeakGenPeakGen
20.6k8080goldbadges234234silverbadges427427bronzebadges
4
Thisissotrue.IamtryingtofixoneissuewhereI'mgettingOOMonAWTthreadbutifIusedifferentnewthread,IamnotgettingOOMissue.AllIcanfindonlineisincreaseheapsizeforAWTthread.
– Ashish
Feb11,2019at5:43
1
@Ash:Yes,fixthecoreprobleminsteadoflookingforplasters.
– PeakGen
Feb12,2019at7:59
GarbagecollectionandthememorymanagementapproachinJavawassupposedtosolveallthesemalloc-dealloccomplicationsofitspredecessors:(OfcourseIcompletelyagreewiththisanswerit'sjustashamethedefaultsdon'tmakeiteasytowritecodewithleandata-structuresthatarecleanedupASAP.
– Davos
Oct11,2019at11:51
5
Idonotagree.Youneedtosetittosomevalueinitially.Ifitturnsouttobeinsufficientitdoesnotnecessarilymeanthatyourapplicationisbad.Maybeyouweretoooptimistic.Itisavalidsolutiontosetittoahighervalueinthiscase.
– ZsoltSky
Jun10,2021at12:30
Addacomment
|
31
Bigcaveat----atmyoffice,wewerefindingthat(onsomewindowsmachines)wecouldnotallocatemorethan512mforJavaheap.ThisturnedouttobeduetotheKasperskyanti-virusproductinstalledonsomeofthosemachines.AfteruninstallingthatAVproduct,wefoundwecouldallocateatleast1.6gb,i.e,-Xmx1600m(mismandatoryotherwiseitwillleadtoanothererror"Toosmallinitialheap")works.
NoideaifthishappenswithotherAVproductsbutpresumablythisishappeningbecausetheAVprogramisreservingasmallblockofmemoryineveryaddressspace,therebypreventingasinglereallylargeallocation.
Share
Improvethisanswer
Follow
editedMar23,2019at8:46
Hearen
6,98122goldbadges4848silverbadges5858bronzebadges
answeredApr14,2009at13:34
DavidDavid
5,74055goldbadges3131silverbadges3939bronzebadges
Addacomment
|
25
VMargumentsworkedformeineclipse.Ifyouareusingeclipseversion3.4,dothefollowing
gotoRun-->RunConfigurations-->thenselecttheprojectundermavenbuild-->thenselectthetab"JRE"-->thenenter-Xmx1024m.
AlternativelyyoucoulddoRun-->RunConfigurations-->selectthe"JRE"tab-->thenenter-Xmx1024m
Thisshouldincreasethememoryheapforallthebuilds/projects.Theabovememorysizeis1GB.Youcanoptimizethewayyouwant.
Share
Improvethisanswer
Follow
editedMar23,2019at8:50
Hearen
6,98122goldbadges4848silverbadges5858bronzebadges
answeredJun9,2011at20:48
loveallloveall
25133silverbadges22bronzebadges
Addacomment
|
24
Iwouldliketoaddrecommendationsfromoracletroubleshootingarticle.
Exceptioninthreadthread_name:java.lang.OutOfMemoryError:Javaheapspace
ThedetailmessageJavaheapspaceindicatesobjectcouldnotbeallocatedintheJavaheap.Thiserrordoesnotnecessarilyimplyamemoryleak
Possiblecauses:
Simpleconfigurationissue,wherethespecifiedheapsizeisinsufficientfortheapplication.
Applicationisunintentionallyholdingreferencestoobjects,andthispreventstheobjectsfrombeinggarbagecollected.
Excessiveuseoffinalizers.
Oneotherpotentialsourceofthiserrorariseswithapplicationsthatmakeexcessiveuseoffinalizers.Ifaclasshasafinalizemethod,thenobjectsofthattypedonothavetheirspacereclaimedatgarbagecollectiontime
Aftergarbagecollection,theobjectsarequeuedforfinalization,whichoccursatalatertime.finalizersareexecutedbyadaemonthreadthatservicesthefinalizationqueue.Ifthefinalizerthreadcannotkeepupwiththefinalizationqueue,thentheJavaheapcouldfillupandthistypeofOutOfMemoryErrorexceptionwouldbethrown.
Onescenariothatcancausethissituationiswhenanapplicationcreateshigh-prioritythreadsthatcausethefinalizationqueuetoincreaseataratethatisfasterthantherateatwhichthefinalizerthreadisservicingthatqueue.
Share
Improvethisanswer
Follow
editedMar23,2019at8:47
Hearen
6,98122goldbadges4848silverbadges5858bronzebadges
answeredMar22,2016at18:35
RavindrababuRavindrababu
46.5k99goldbadges236236silverbadges206206bronzebadges
Addacomment
|
19
Yes,with-XmxyoucanconfiguremorememoryforyourJVM.
Tobesurethatyoudon'tleakorwastememory.TakeaheapdumpandusetheEclipseMemoryAnalyzertoanalyzeyourmemoryconsumption.
Share
Improvethisanswer
Follow
editedMar23,2019at8:53
Hearen
6,98122goldbadges4848silverbadges5858bronzebadges
answeredOct9,2008at8:22
kohlermkohlerm
2,58611goldbadge1717silverbadges2020bronzebadges
1
2
JVMJ9VM007ECommand-lineoptionunrecognised:-XmxCouldnotcreatetheJavavirtualmachine.Downvote
– PhilipRego
Jan15,2019at22:28
Addacomment
|
11
Followbelowsteps:
Opencatalina.shfromtomcat/bin.
ChangeJAVA_OPTSto
JAVA_OPTS="-Djava.awt.headless=true-Dfile.encoding=UTF-8-server-Xms1536m
-Xmx1536m-XX:NewSize=256m-XX:MaxNewSize=256m-XX:PermSize=256m
-XX:MaxPermSize=256m-XX:+DisableExplicitGC"
Restartyourtomcat
Share
Improvethisanswer
Follow
editedMar23,2019at8:46
Hearen
6,98122goldbadges4848silverbadges5858bronzebadges
answeredOct7,2013at10:56
PradipBhattPradipBhatt
65899silverbadges1515bronzebadges
Addacomment
|
9
BydefaultfordevelopmentJVMusessmallsizeandsmallconfigforotherperformancerelatedfeatures.Butforproductionyoucantunee.g.(InadditionitApplicationServerspecificconfigcanexist)->(Iftherestillisn'tenoughmemorytosatisfytherequestandtheheaphasalreadyreachedthemaximumsize,anOutOfMemoryErrorwilloccur)
-Xms
延伸文章資訊
- 1java.lang.OutOfMemoryError: Java heap space 解决方法
java.lang.OutOfMemoryError: Java heap space 解决方法. 这个问题的根源是jvm虚拟机的默认Heap大小是64M,可以通过设置其最大和最小值来实现.设置...
- 2OutOfMemoryError系列(1): Java heap space - CSDN博客
本文通过实例来分析java.lang.OutOfMemoryError: Java heap space 问题产生的原因, 以及相关的解决方案.
- 3java.lang.OutOfMemoryError Java heap space? 怎麼解?
java.lang.OutOfMemoryError Java heap space? 怎麼解? 前言. 因為工作關係,其實不只會碰到node.js 有時候還會協助其他 ...
- 4Stack Memory and Heap Space in Java - Baeldung
Heap space is used for the dynamic memory allocation of Java objects and JRE classes at runtime. ...
- 5报错:Java heap space - 帆软帮助文档
... 模板时就会占用Java 虚拟机JVM 的大量内存,超过内存就会出现报java.lang.OutOfMemoryError:Java heap space 内存溢出的错误,具体报错如下: ...