Jmeter java heap space ошибка как исправить

To optimize OutOfMemoryError these steps should be followed:

  • Increase the Java Heap Size:

JMeter is a Java tool it runs with JVM. To obtain maximum capability, we need to provide maximum resources to JMeter during execution.First, we need to increase heap size (Inside JMeter bin directory, we get jmeter.bat/sh).

HEAP=-Xms512m –Xmx512m

It means default allocated heap size is minimum 512MB, maximum 512MB. Configure it as per you own machine configuration. It should also be kept in mind that OS also need some amount of memory, so all of the physical RAM shouldn’t be allocated.

  • Run Tests in Non-GUI Mode:

JMeter is Java GUI application. It also has the non-GUI edition which is very resource intensive(CPU/RAM). If we run Jmeter in non-GUI mode , it will consume less resource and we can run more thread.

  • Disable ALL Listeners during the Test Run. They are only for debugging and use them to design the desired script.

Listeners should be disabled during load tests. Enabling them causes additional overheads, which consume valuable resources that are needed by more important elements of your test.

  • Use Up-to-Date Software:

Java and JMeter should be kept updated.

  • Decide Which Metrics You Need to Store:

When it comes to storing requests and response headers, assertion results and response data can consume a lot of memory! So it is wise try not to store these values on JMeter unless it’s absolutely necessary.

  • Tweak JVM:

The following JVM arguments in JMeter startup scripts can also be added or modified:

1. Add memory allocation rate:

NEW=-XX:NewSize=128m -XX:MaxNewSize=512m

This means memory will be increased at this rate.

2.-server — this switches JVM into “server” mode with runtime parameters optimization. In this mode, JMeter starts more slowly, but the overall throughput will be higher.

3. -d64 — While using a 64-bit OS, using this parameter can explicitly tell JVM to run in 64-bit mode.

4. -XX:+UseConcMarkSweepGC — this forces the usage of the CMS garbage collector. It will lower the overall throughput but leads to much shorter CPU intensive garbage collections.

5. -XX:+DisableExplicitGC — this prevents applications from forcing expensive garbage collections and helps avoid unexpected pauses.

For better and more elaborated understanding, this blog about 9 Easy Solutions for a JMeter Load Test “Out of Memory” Failure is helpful.

In this article, we’ll discuss JMeter memory profiling, and you’ll learn nine ways to get the maximum load on your JMeter test without changing your current hardware setup.

Table of Contents:

  • How do I allocate more memory to JMeter?
  • Increase the Java Heap Size
  • Use Up-to-Date Software
  • Run Tests in Non-GUI Mode
  • Use Listeners Wisely
  • Decide Which Metrics You Need to Store
  • Select the Correct Correlation Option
  • Use Assertions Sparingly
  • Check Your Scripting Language
  • Still Not Working?
  • Want to Learn More About JMeter & Load Testing?

First thing’s first: How many times have you seen this error on your JMeter load test?

Test failed! java.lang.OutOfMemoryError: Java heap space

9 Easy Solutions for a JMeter Load Test “Out of Memory” Failure

How do I allocate more memory to JMeter?

If you have received this out of memory error, there are easy ways to get around it. In this article, I’ll show you nine ways to get the maximum load on your JMeter test without changing your current hardware setup including increasing the Java heap size, strategically using listeners, and much more. 

🚀Try BlazeMeter today for performance testing at scale >>

1.  Increase the Java Heap Size

The JMeter process runs in the Java Virtual Machine (JVM) under various settings and arguments. The Java Heap Space (as referred to in the error message) is the memory the JVM takes from the underlying operating system to allocate space for the creation of necessary objects.

JMeter’s default configuration (see jmeter.bat for Windows or jmeter for non-Windows systems scripts) assumes a heap space of 1024 megabytes only. This is actually pretty low considering  many modern smartphones have up to four times more! If your test is running massive objects which go over 1024Mb, you’ll get an OOM error and your test will fail.

Fortunately, there’s a simple solution. Just increase the maximum heap size to ~80% of your total available physical RAM. To do this, find the following line in your JMeter startup script:

HEAP=-Xms1g -Xmx1g

Now change the -Xmx value accordingly. For example: if you want to set the maximum heap size to 4 gigabytes, you’ll need to change the line to: HEAP=»-Xms1g -Xmx4gm»

To apply the change, you’ll need to restart JMeter.

2. Use Up-to-Date Software

Your test might fail if your software is out of date. Make sure you’re using the most recent versions of the following:

  1. Java  — use the latest 64-bit version of Java SE JDK or Server JRE where possible
  2. JMeter — it’s always best to use the latest version of JMeter as the new releases contain performance improvements and bug fixes in addition to any new features.  
  3. JMeter Plugins (or other 3rd-party libraries) — for the same reasons as Java and JMeter

3. Run Tests in Non-GUI Mode

NEVER run a load test on the JMeter GUI! Use it only for test recording, development, and debugging. JMeter is simply not designed to produce high loads in GUI mode, which means that it will not only freeze — but it will also consume loads of resources and produce unreliable load test results.

I recommend running load tests in the command-line mode, Ant tasks, or Maven plugins —  but never the GUI.

If you want more information on the available options, check out Five Ways To Launch a JMeter Test without Using the JMeter GUI.

4. Use Listeners Wisely

Disable ALL Listeners During the Test Run

Listeners should be disabled during load tests. Enabling them causes additional overheads, which consume valuable resources that are needed by more important elements of your test.

You can open the .jtl results file with any listener you want after the test completes and perform its analysis.

If you want to view metrics during the test execution, try running your JMeter test via the Taurus framework. This means you’ll be able to view report statistics via your console and or web interface.  

JMeter Test on Taurus

5. Decide Which Metrics You Need to Store

Configure JMeter to ensure that it will only save the metrics that you absolutely need. You can control what to store by adding relevant lines to the user.properties file (you can find this in the /bin folder of your JMeter installation). 

JMeter Metrics

For example: with listeners like the Active Threads Over Time Listener or Response Times vs Threads, you’ll need to store the number of currently active threads (as it isn’t done by default). To enable this, you’ll need to add the line “jmeter.save.saveservice.thread_counts=true” to the user.properties file.

Similarly, to control the way results are saved, search for the Results File Configuration section of the jmeter.properties file (you’ll also find this in the JMeter /bin folder) and inspect the names and default values of properties that have names starting with: “jmeter.save.saveservice”. After figuring out the appropriate configuration, you can amend the user.properties file by specifying which metrics you need to store and which you don’t require.

Don’t forget that when it comes to storing requests and response headers, assertion results and response data can consume a lot of memory! So try not to store these values on JMeter unless it’s absolutely necessary.  

Check out 2 Awesome Tips for Reducing Memory Usage in JMeter for more information. 

6. Select the Correct Correlation Option

If you need to extract something from the previous response, try using the Regular Expression Extractor.

If for some reason it’s not possible (i.e. you need to get multiple values from HTML using multiline complicated regex) try one of the following:

  1. If the page has a very complex DOM but the number of styles is relatively low — go for the CSS/JQuery Extractor

  2. If the number of styles is high and DOM is fairly simple — use the XPath Extractor

If you have enough time you can experiment and take memory footprints for each of the PostProcessors. This will clearly show you which one is better.  But remember — this approach will have to be applied to every single page as different applications have different responses.  

7. Use Assertions Sparingly

Every test element added to the test plan will be processed — and this takes CPU time and memory. This also applies to all your Assertions, and is especially true for Compare Assertions —  which consumes a lot of resources and memory. Only use the assertions you need and, even then, just use the amount that are absolutely required.

8. Check Your Scripting Language

JMeter supports quite a lot of scripting languages. However, if you’re using a scripting-based sampler to create the actual load, you’ll need to use the JSR223 Sampler and “Groovy” as a language.

The Groovy scripting engine implements the Compilable interface. So if your script is well designed, you’ll get a performance comparable with pure Java code. If you want more detailed explanations and scripting best practices, check out the guide: Beanshell vs JSR223 vs Java JMeter Scripting: The Performance-Off You’ve Been Waiting For!

If you need to do something very simple (i.e. converting a variable to a property, setting the While Controller condition, getting the current iteration number etc.), you can use the JavaScript or Beanshell engines as they’re available out of the box and JavaScript is used under the If Controller’s hood. However, when you start creating the load via the scripting test element, go for JSR223 and Groovy.

9. “Tweak” Your JVM

You can also add or modify the following JVM arguments in your JMeter startup scripts:

  1. locate the NEW=»-XX:NewSize=128m -XX:MaxNewSize=128m» line in the JMeter startup script. Uncomment it and increase the values to match the ones you set for HEAP

  2. -server — this switches JVM into “server” mode with runtime parameters optimization. In this mode JMeter starts more slowly, but your overall throughput will be higher

  3. -d64   — if you have a 64-bit OS, use this parameter to explicitly tell JVM to run in 64-bit mode

  4. -XX:+UseConcMarkSweepGC — this forces the usage of the CMS garbage collector. It will lower the overall throughput but leads to much shorter CPU intensive garbage collections.

  5. -XX:+DisableExplicitGC — this prevents applications from forcing expensive garbage collections and helps avoid unexpected pauses. In general, garbage collection tuning is a very big topic. If you think that JMeter’s throughput could be better and it doesn’t fully utilize JVM, OS and machine resources, try using JConsole or VisualVM to monitor the JMeter process and inspect the heap size usage, GC interval, the time the system spends in garbage collection etc.  Ideally, the GC should look like a “pulse” of a healthy human being. The garbage collector should fire often enough to prevent OOM — but not so much that its impact is strongly felt.

Still Not Working?

If you’ve tried all of the above points, but your machine still can’t produce the load you require, you have two options:

  1. Employ distributed testing by adding more hosts and configuring them manually. JMeter supports the distributed mode when one master machine orchestrates several slaves, meaning the load comes from several generators. Remember that the master machine doesn’t generate any load, so you’ll need three hosts to increase throughput by a factor of two.

  2. Run a JMeter test in the BlazeMeter cloud. This is very simple to set up and gives a lot of valuable features, such as: advanced results analysis, the ability to compare different test runs, and integrations with automation and monitoring tools.

Want to Learn More About JMeter & Load Testing?

Check out BlazeMeter University!

This blog post was updated in July 2021 for accuracy.

START TESTING NOW

Related Resources

  • How to Use JMeter’s Constant Throughput Timer

If you’re here, it’s because you’ve probably experienced Java Heap Space exceptions while running JMeter. Isn’t it?

JMeter Out Of Memory exceptions happen during a heavy load tests, with the following log lines appearing in jmeter.log:

2017/10/01 13:35:16 ERROR - jmeter.threads.JMeterThread: Test failed! java.lang.OutOfMemoryError: Java heap space

It can also be a message like Unable to create new native Thread. Don’t panic!

You’ll learn 12 ways to get ride of memory issues and get a better understanding of how the JVM works.

Use Java JDK NOT JRE

As per Java Garbage Collection handbook:

By default the JVM is configured to throw Out Of Memory errors if **it spends more than 98% of the total time doing GC and when after the GC only less than 2% of the heap is recovered.

Here is the difference:

  • JRE: Java Runtime Environment. It is basically the Java Virtual Machine where your Java programs run on. It also includes browser plugins for Applet execution.
  • JDK: It’s the full featured Software Development Kit for Java, including JRE, and the compilers and tools (like JavaDoc, and Java Debugger) to create and compile programs.

The reason to go with a JDK is that it contains a server optimized compiler which is better at optimizing Java code execution, thus JMeter Execution.

From Chapter 2 of the whitepaper (The Java HotSpot Performance Engine Architecture):

The Server VM contains an advanced adaptive compiler that supports many of the same types of optimizations performed by optimizing C++ compilers, as well as some optimizations that cannot be done by traditional compilers, such as aggressive inlining across virtual method invocations. This is a competitive and performance advantage over static compilers. Adaptive optimization technology is very flexible in its approach, and typically outperforms even advanced static analysis and compilation techniques.

Increase Java Heap Size

JMeter is a Java program which relies on the Java Virtual Machine. The JVM can be tuned to increase the allocated RAM. When a Java program requires fair an amount of memory, like JMeter, it’s common to increase the allocated RAM.

By default, JMeter can use up to 512MB of RAM, as stated in jmeter.sh or jmeter.bat launch scripts:

1
2
3
4
5

# This is the base heap size -- you may increase or decrease it to fit your
# system's memory availability:
HEAP="-Xms512m -Xmx512m"

This is a pretty conservative setting to ensure JMeter can run even on tiny computers. Let me explain the settings:

  • -Xms512m: tells the JVM to allocated at least 512MB of RAM,
  • -Xmx512m: tells the JVM to allocated at most 512MB of RAM.

For example, if you want to allocate between 1024MB and 2048MB of RAM to the JVM, use the following settings by editing your JMeter startup script:

1
HEAP="-Xms1024m -Xmx2048m"

Upgrade Java and JMeter

Make sure to use the most recent versions of:

  • Java: use the latest 64 bits Java Virtual Machine, as it allows to use more than 1536MB or RAM as Xmx,
  • JMeter: latest JMeter versions usually contain many fixes and improvements,
  • JMeter Plugins: make sure to use the latest JMeter Plugins,
  • Operating System: upgrade your operating system to the latest version.

Generally speaking, avoid using old software versions otherwise you may encounter bugs that have been fixed in latest versions.

JMeter Non-Gui Mode

You can execute JMeter test from the command line without launching the UI (which consumes a lot of memory):

jmeter -n -t scenario.jmx

  • -n: runs JMeter in non-GUI mode,
  • -t: specifies the path to source .jmx script to run.

Disable Listeners

Many of the JMeter listeners consume a lot of memory because they keep all the results in the RAM. You should disable or remove them all before running a load test to avoid putting pressure on the JVM with unnecessary results kept in main memory.

Tune JMeter SaveService

JMeter’s SaveService manages the data which is written into the JTL result file. You can vastly improve the throughput by reducing the amount of data being written into the JTL files by editing the jmeter.properties file.

The properties below are pretty well optimized and can be used as default settings:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# true when field should be saved; false otherwise

# assertion_results_failure_message only affects CSV output
#jmeter.save.saveservice.assertion_results_failure_message=true
#
# legitimate values: none, first, all
#jmeter.save.saveservice.assertion_results=none
#
#jmeter.save.saveservice.data_type=true
#jmeter.save.saveservice.label=true
#jmeter.save.saveservice.response_code=true
# response_data is not currently supported for CSV output
#jmeter.save.saveservice.response_data=false
# Save ResponseData for failed samples
#jmeter.save.saveservice.response_data.on_error=false
#jmeter.save.saveservice.response_message=true
#jmeter.save.saveservice.successful=true
#jmeter.save.saveservice.thread_name=true
#jmeter.save.saveservice.time=true
#jmeter.save.saveservice.subresults=true
#jmeter.save.saveservice.assertions=true
#jmeter.save.saveservice.latency=true
# Only available with HttpClient4
#jmeter.save.saveservice.connect_time=true
#jmeter.save.saveservice.samplerData=false
#jmeter.save.saveservice.responseHeaders=false
#jmeter.save.saveservice.requestHeaders=false
#jmeter.save.saveservice.encoding=false
#jmeter.save.saveservice.bytes=true
# Only available with HttpClient4
#jmeter.save.saveservice.sent_bytes=true
#jmeter.save.saveservice.url=false
#jmeter.save.saveservice.filename=false
#jmeter.save.saveservice.hostname=false
#jmeter.save.saveservice.thread_counts=true
#jmeter.save.saveservice.sample_count=false
#jmeter.save.saveservice.idle_time=true

For example, jmeter.save.saveservice.samplerData=true can really hurt JMeter performances because it writes down all the responses data. Avoid saving anything related to response data, response headers or assertions data unless you absolutely need them. They can consume a great amount of memory.

Json Path Extractor or XPath Extractor should be avoided. They consume a lot of memory because they need to convert the response body into a complex data structure in memory.

Use Few Assertions

Assertions increase CPU and memory usage because they usually need to process the response data sent by the server.

Use The Right Script Engine

Go for JSR223 + Groovy scripting. It’s the fastest scripting engine in JMeter. Beanshell, Javascript and others should be avoided because the performance penalty can be huge compared to Groovy.

Further Tweak JVM Settings

WARNING: danger zone. Tweaking the JVM is mostly not required and can lead to problems. However, if you really want to squeeze the last bit of performance out of the JVM, you can use the following JVM settings (at your own risk):

  • -server: This switches JVM into “server” mode with runtime parameters optimization, as explained above it enables more aggressive compiler optimizations,
  • -XX:+UseConcMarkSweepGC: Enables concurrent Mark Sweep GC which can improve CPU usage on multi-core CPUs,
  • -XX:+DisableExplicitGC: Prevents explicit GC Calls. Unfortunately (and in spite of the disclaimers in the documentation), many developers decide they know better than the JVM and call the Garbage Collector programmatically to collect memory. I’m aware of many instances where the -XX:+DisableExplicitGC improved the production environment and zero instances where there were any negative side effects.

Monitor JMeter JVM

JConsole is a monitoring tool which can be used to view JMeter’s JVM overall performance counters like Thread Count or memory usage.

Distributed Tests

At some point, you won’t be able to further improve JMeter’s memory usage if you need to run a massive amount of concurrent users. You won’t be able to run 10.000 concurrent users from a single machine, that’s simply not working (and not simply because of CPU and memory usage, but also network usage).

You have two options left:

  • Run Distributed JMeter tests by your own, Distributed JMeter testing is tricky and requires a lot of knowledge. Always make sure to configure each JMeter instance running on each computer with the same SaveService settings, same JVM settings etc. You will have to setup each load generator manually and edit each configuration file,

  • Run Distributed JMeter tests on OctoPerf. Needless to say this will save you a tremendous amount of time.

Share you own JMeter Optimization tips and tricks with the community in the comments below!

I’m getting the following error:

out of memory error : java heap space error while running jmeter script for long run say 20 hrs.

I have set 10 GB heap size to run 10 threads only.

Could it be my application’s bug? How can I be sure that this is application’s bug not a jmeter issue?

trincot's user avatar

trincot

309k35 gold badges240 silver badges282 bronze badges

asked Oct 20, 2017 at 13:13

Sourav's user avatar

JMeter is a Java application with a GUI. It also supports a non-GUI mode which is less resource intensive(CPU/RAM). If we run JMeter in non-GUI mode, it will consume less resource and we can run more threads.

  • Disable ALL Listeners during the Test Run. They are only for debugging and use them to design the desired script.

Listeners should be disabled during load tests. Enabling them causes additional overheads, which consume valuable resources that are needed by more important elements of your test.

  • Use Up-to-Date Software:

Java and JMeter should be kept updated.

  • Decide Which Metrics You Need to Store:

When it comes to storing requests and response headers, assertion results and response data can consume a lot of memory! So it is wise try not to store these values on JMeter unless it’s absolutely necessary.

JMeter SaveService badly configured: Check if you are saving requests and responses in your JTL.

For better and more elaborated understanding, this blog about 9 Easy Solutions for a JMeter Load Test “Out of Memory” Failure is helpful.

Daniel Trugman's user avatar

answered Oct 20, 2017 at 13:25

Masud Jahan's user avatar

Masud JahanMasud Jahan

3,3982 gold badges21 silver badges34 bronze badges

Getting below error message during our load test in jmeter version 5.1.1.

2020-01-17 01:30:00,644 ERROR o.a.j.JMeter: Uncaught exception: 
java.lang.OutOfMemoryError: Java heap space

How much Max memory should we increase in jmeter batch file using command:

HEAP=-Xms1g -Xmx1g -XX:MaxMetaspaceSize=256m

Prome's user avatar

Prome

1,0169 silver badges24 bronze badges

asked Jan 17, 2020 at 6:49

user41456's user avatar

BlazeMeter article recommends:

Just increase the maximum heap size to ~80% of your total available physical RAM.

HEAP=»-Xms512m -Xmx512m»

Now change the -Xmx value accordingly. For example: if you want to set the maximum heap > size to 4 gigabytes, you’ll need to change the line to: HEAP=»-Xms512m -Xmx4096m»

Community's user avatar

answered Jan 17, 2020 at 7:41

Prome's user avatar

PromeProme

1,0169 silver badges24 bronze badges

As per Optimal Heap Size chapter:

«If the occupancy of the Java heap is too high, garbage collection occurs frequently. If the occupancy is low, garbage collection is infrequent but lasts longer… Try to keep the memory occupancy of the Java heap between 40% and 70% of the Java heap size… The highest point of occupancy of the Java heap is preferably not above 70% of the maximum heap size, and the average occupancy is between 40% and 70% occupancy. If the occupancy goes over 70%, resize the Java heap.»

«A correctly sized Java heap should always have a memory occupancy of between 40% and 70% of the maximum Java heap size. To ensure that the occupancy does not exceed 70%, set the maximum Java heap size to at least 43% larger than the Maximum occupancy value provided by GCMV. This setting then makes the Maximum value 70% of the Java heap and the average to be above 40% of the Java heap size.»

enter image description here

So make sure that:

  1. JMeter has enough headroom to operate
  2. Garbage Collection doesn’t happen too often

Use JVisualVM or JMeter PerfMon Plugin to monitor the heap usage by JMeter and tune minimum/maximum according to the above 40% — 70% rule

Community's user avatar

answered Jan 20, 2020 at 11:43

Dmitri T's user avatar

Dmitri TDmitri T

13.1k1 gold badge14 silver badges18 bronze badges

Problem Statement:

Sometimes, JMeter throws a heap dump along with out of memory error while executing the load test.

How to check the error?

  1. Refer to the JMeter log file in bin folder apache-jmeter-<version> -> bin -> jmeter.log
  2. You may see the error like this.
java.lang.OutOfMemoryError: Java heap space Dumping heap to
    java_pid1102.hprof ... Heap dump file created [851645907 bytes in
    71.244 secs] Exception in thread "Thread Group 1-100" java.lang.OutOfMemoryError: Java heap space Exception in thread
    "Thread Group 1-100" java.lang.OutOfMemoryError: Java heap space
    Exception in thread "Thread Group 1-100" java.lang.OutOfMemoryError:
    Java heap space Exception in thread "Thread Group 1-100"
    java.lang.OutOfMemoryError: Java heap space

If you executed the test in GUI mode then click on the error icon (yellow triangle with exclamatory mark) on the right corner of the JMeter and read the error.

JMeter - How to increase heap size

Figure 01

Reason:

The allocated heap size to JVM is not enough to execute the test with the given load (thread).

Solution:

There could be possibly different ways to solve this problem but among them, one of the common solutions is to increase the heap size set for JMeter.

Procedure to increase heap size in JMeter:

  1. Go to the bin folder of JMeter
    apache-jmeter-<version> -> bin
  2. Right-click and open jmeter.bat file in notepad or notepad++
  3. Search for the keyword ‘set Heap’
  4. You can see the default heap size (1 GB – may vary in your JMeter version)
    set HEAP=-Xms1g -Xmx1g -XX:MaxMetaspaceSize=256m
  5. Change the -Xms (initial heap size) and -Xmx (maximum heap size) values. You can increase these values up to 80% of total heap. In my case, I just increased the max heap size value. Refer to the below arguments:
    set HEAP=-Xms1g -Xmx2g -XX:MaxMetaspaceSize=256m
  6. To check the total allocated heap to JVM, run the below command in the command prompt:
    java -XX:+PrintFlagsFinal -version | findstr /i “HeapSize PermSize ThreadStackSize”

JMeter - How to increase heap size

Figure 02

How to validate the applied changes?

  1. Launch a new instance of JMeter
  2. Add a ‘Thread Group‘
  3. Add a ‘JSR223 Sample’ under the ‘Thread Group’
  4. Paste the below code in the ‘Script’ section
java.lang.management.ManagementFactory.getRuntimeMXBean().getInputArguments().each {
    log.info("Effective JVM argument: " + "$it")
}
  1. Run the test
  2. Check the JVM argument values in the log by clicking the yellow colour triangle in the right corner.

Figure 03: JVM Arguments

7 ответов

Похоже, у вас просто отсутствует Java Heap Space. Это нормально, так как JMeter по умолчанию имеет очень низкое распределение кучи. Он управляется с помощью параметра -Xmx.

В jmeter.bat или jmeter.sh script есть строка, в которой рекомендуется запустить JMeter как

JVM_ARGS="-Xms512m -Xmx512m" jmeter.sh

Вы можете попробовать увеличить максимальную кучу, пока не прекратите получать эти ошибки. Я бы рекомендовал установить его примерно на 80% вашей аппаратной ОЗУ.

Также рассмотрите статью JMeter Performance and Tuning Tips, чтобы отключить прослушиватели, потребляющие память, не накладывать надписи, эффективно использовать постпроцессоры и т.д.

Dmitri T
18 дек. 2013, в 09:17

Поделиться

После увеличения размер кучи в файле bat удалит весь прослушиватель из плана тестирования. Затем запустите ваш script и увидите волшебство. Теперь вы не получите ошибка из памяти в jmeter
Наслаждайтесь!

Himanshu Tewari
05 фев. 2014, в 13:39

Поделиться

в Jmeter 3.x. для решения этой проблемы есть два шага.

Шаг 1, чтобы изменить память JVM в пакетном файле JMeter

##   ==============================================
##   Environment variables:
##   JVM_ARGS - optional java args, e.g. -Dprop=val
##
##   e.g.
##   JVM_ARGS="-Xms512m -Xmx512m" jmeter etc.
##
##   ==============================================

это значение по умолчанию в jmeter.sh, в соответствии с вашей средой:

JVM_ARGS="-Xms512m -Xmx2048m"

в jmeter.bat:

set JVM_ARGS=-Xms512m -Xmx2048m

Шаг 2, чтобы изменить HEAP = «- Xms512m -Xmx512m» в пакетном файле JMeter:

в jmeter.sh

HEAP="-Xms512m -Xmx2048m"

в jmeter.bat:

set HEAP=-Xms512m -Xmx2048m

Dang
27 дек. 2017, в 11:02

Поделиться

Мой один лайнер для этого на Mac (jmeter — скрипт bash в этом случае):

$ JVM_ARGS = «-Xms4g -Xmx4g -XX: NewSize = 4g -XX: MaxNewSize = 4g» && export JVM_ARGS && jmeter

Animesh
07 дек. 2018, в 13:06

Поделиться

Существует много причин, по которым JMeter потребляет много памяти:

  • Использование и злоупотребление Слушатели пользовательского интерфейса,
  • Запуск теста в режиме пользовательского интерфейса: вместо этого выполните тест в пакетном режиме
  • JMeter SaveService плохо настроен: вы сохраняете запросы и ответы в JTL?
  • Слишком много потоков на генератор нагрузки JMeter? Обычно менее 1000 на двигатель должно быть в порядке, но это также зависит от сложности script. См. Удаленное тестирование для запуска JMeter в Распределенный режим.

Тонкая настройка кучи — это всего лишь один из способов устранения этих проблем:

JVM_ARGS="-Xms512m -Xmx512m" jmeter.sh

Отъезд JMeter Out Of Memory: 12 способов исправить их для еще более ценных советов.

Jerome L
19 окт. 2017, в 08:28

Поделиться

Откройте bin/jmeter.bat на окнах или bin/jmeter.sh на linux,
найдите эту строку:

set HEAP=-Xms512m -Xmx512m

Эта переменная передается как аргумент jmeter при запуске.
Увеличьте значение heapsize по умолчанию следующим образом:

set HEAP=-Xms1024m -Xmx1024m

Вы можете добавить больше места, если у вас есть доступ, и если jmeter нужно больше.
Надеюсь, что это поможет.

user4212639
18 май 2017, в 15:20

Поделиться

также вы всегда должны использовать запуск тестового не-gui-режима.

user6406388
03 май 2017, в 21:33

Поделиться

Ещё вопросы

  • 0session_start неисправность php
  • 1Это правильный способ издеваться над HttpContextBase, HttpRequestBase и HttpResponseBase для модульного тестирования файлов cookie?
  • 1Как выровнять два текста по горизонтали с фоном, используя любой макет в Android?
  • 0Свойство, которое не верно для классов
  • 0Как выровнять навигационную панель по нижней части окна без зазора между кнопками и краем окна
  • 0Слайдер Jquery не работает на iPad отлично работает в браузере
  • 0Безопасные / небезопасные проблемы загрузки jQuery CDN
  • 1Отображение части ImageIcon
  • 1Отправить письмо программно
  • 0Yii2 RBAC Ошибка DbManager Вызов функции-члена getRole () со значением NULL
  • 0Почему существует бесконечный цикл? C ++
  • 0Директива общего доступа между приложениями в AngularJS
  • 0Почему мой угловой пейджинг не работает?
  • 0Экспорт Excel из таблицы MySQL
  • 1Можно ли установить полностью прозрачный фон для макета класса обслуживания
  • 0заменить оператор new на malloc
  • 1unity3d — Как отключить кнопки на GUI.Box, когда другой GUI.Box находится сверху?
  • 0ZF2 & Doctrine2 getServiceConfig функция подключения к фабрикам
  • 0symfony2: нельзя вставить в форму слияния один-к-одному
  • 0Стильные фрагменты текста, которые не обернуты в div
  • 1Как дублировать поток
  • 1Как сделать SSH с одного компьютера на другой, используя Java
  • 0Использование GDI + в консольном приложении
  • 0удалить элемент из локального хранилища
  • 0Как установить объект файла как ngModel, используя $ setViewValue (file)
  • 1Identity Toolkit API ранее не использовался в проекте или он отключен
  • 0Как использовать mysql после установки более старой версии mariadb через homebrew?
  • 1Не удается создать NotificationCompat.Builder в Android O
  • 0Плагин Firebreath: Как получить свойства документа в части c ++?
  • 1Что нужно установить на TFS сервер
  • 1Преобразование миллисекунд в объект даты UTC с часовым поясом UTC
  • 1Можно ли перегрузить объявление cpdef на Cython .pxd?
  • 0Как я могу вставить автоматически определенный день и определенное время в MySQL Вставить запрос
  • 1WCF замедляется с несколькими запросами
  • 1Ограничить текстовое поле принимать цифры и буквы только в приложении магазина Windows 8
  • 0создать действие javascript из результата оператора php if / else
  • 1Объединение данных в цикле
  • 1Ошибка tkinter.Text () (_tkinter.TclError: ожидаемое целое число, получено «sans»)
  • 0На Hover добавить / удалить класс для div ребенка
  • 0Где мне нужно развернуть файлы приложения после входа в openshift с помощью filezila
  • 1Эффективный для памяти способ хранения значений bool и NaN в пандах
  • 0Qt: joinMulticastGroup для всего интерфейса
  • 0невозможно отправить изображение base 64 на сервер с угловым js
  • 0Symfony 2 PHP Template Engine рендеринг объектов
  • 1перераспределить данные в гауссовом распределении с помощью pd.DataFrame
  • 1Подсчет символа «е»
  • 1Сбой смешивания с ObservableAsPropertyHelper
  • 0Вставка сохраняет только первую цифру, остальные игнорируются
  • 0Панель инструментов кнопки jquery UI с меню
  • 0Генерация PDF от AngularJS

Jmetr — это инструмент тестирования производительности с открытым исходным кодом, разработанный Java, который поддерживает тест на моделирование и последующее тестовое прессование в тестировании производительности, но иногда, когда аналоговые запросы параллелизма являются большие или длинные, возникает вероятность давления, и даже шанс на стресс будет допустить исключение — — переполнение памяти,

Вот как решить внутренние задания и связанные с ними пункты знаний. Отказ Отказ

Давайте посмотрим на утечки памяти, мы часто говорим, какая переполнение памяти?
Утечка памяти означает, что вы не выпущены вовремя после того, как ваше приложение использует ресурсы, не вызывая необходимости ресурсов в памяти приложения, что является описанием состояния;
Переполнение памяти означает, что поданная вами память больше не доступна, стек достиг максимального значения системных настроек, что, в свою очередь, приводит к краху, что является результатом этого.
Обычно из-за утечек памяти память стека увеличивается, а переполнение памяти брошена.

В процессе использования теста JMeter, если переполняется памятью, это подсказка, как правило, появится: Java.lang.OutofmemoryError: Java Heap Space: значение состоит в том, что внутренняя часть стога переполняется, недостаточно.

Говоря о памяти стека, чтобы представить соответствующие знания стека:

Для более подробного содержания, пожалуйста, обратитесь к здесь:Baidu Encyclopedia: стек

Решение переполнения памяти: отрегулируйте размер памяти стека

шаг:

1, откройте файл установки JMeter (можетБлокнот ++Открыть), файл jmeter.bat под каталогом bin:

2. Найдите содержимое заданного кучи, в соответствии со специфическими потребностями для изменения размера значения кучи, а также значение памяти нового назначения:

По умолчанию здесь есть:

set HEAP=-Xms512m -Xmx512m
set NEW=-XX:NewSize=256m -XX:MaxNewSize=256m

Измените его:

set HEAP=-Xms512m -Xmx4096m
set NEW=-XX:NewSize=256m -XX:MaxNewSize=512m

ПРИМЕЧАНИЕ. В общем, максимальное значение кучи не должно превышать половину физической памяти. В противном случае Jmeter работает медленно, а коробка или даже переполнение памяти (поскольку механизм сборки мусора Java динамически распределяется,

Когда он настроен, это займет много памяти), а память, выделенная новой, не слишком велика!

3. После завершения модификации выключите файл, перезапустите JMeter Can:

PS:Когда количество потоков необходимо моделироваться, большой, необходимо принять распределенное измерение напряжения в соответствии с конкретной ситуацией. Этот метод модификации стека применим только, а не универсальный!

Трансфер из: https://www.cnblogs.com/imyalost/p/7901064.html.

Like this post? Please share to your friends:
  • Jira система отслеживания ошибок
  • Jira ошибка 500
  • Jino ошибка 502
  • Junkers euromaxx ошибка f0
  • Jinn client ошибка создания com объекта 1c