Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Memory growth during a Java screenshot loop is a symptom, not a diagnosis. First determine whether the retained memory is in the Java heap, in native/off-heap JVM memory, or in a separately running browser process. Then identify which object, page state, image buffer, or browser resource remains reachable. Increasing -Xmx before doing that can hide the cause and postpone an out-of-memory failure.

1. Identify which process and memory pool is growing

Screenshot stacks do not all have the same architecture. HtmlUnit parses pages, runs JavaScript, and manages browser state inside the hosting JVM. Playwright Java and most Selenium setups control a browser that normally runs in separate processes. A Java heap dump can explain HtmlUnit objects or retained screenshot arrays, but it cannot account for all browser-native memory. Conversely, Chrome DevTools cannot show every Java object retained by your application.

Measure comparable points

  1. Run a repeatable loop against the same representative URL or page set. Record the capture count, viewport and page dimensions, full-page versus element mode, device scale, image format, and concurrency.
  2. At consistent points (for example, after a batch and an explicit test GC), record Java heap used, committed heap, process RSS/native memory, and browser or renderer memory separately.
  3. Record whether each result is written to disk, kept as a byte[], converted to Base64, placed on a queue, or retained in a collection for later processing.
  4. Compare the live retained set after warm-up. RSS or committed heap does not have to fall immediately after every iteration; a stable post-GC live set is the useful target.

Oracle’s Java 21 troubleshooting guidance recommends heap dumps for leak analysis and describes Java Flight Recorder heap statistics for seeing object growth over time. See Oracle’s memory-leak troubleshooting guide.

Capture heap evidence

Take at least two snapshots at different capture counts and compare retained classes and paths to GC roots:

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
jcmd <pid> GC.heap_dump heap-10k.dmp
jcmd <pid> GC.heap_dump heap-50k.dmp

You can also use jmap, JConsole, or enable -XX:+HeapDumpOnOutOfMemoryError. Look for application queues, maps, listener objects, page/driver wrappers, strings containing Base64 data, and arrays whose retained size grows with the loop. Do not treat a larger committed heap as proof of a leak.

2. Audit ownership and close resources at the right boundary

For every iteration, write down who owns the browser, context or session, page/tab, driver, streams, image bytes, and result queue. Close each object at the lifecycle boundary documented by the library you actually use. A common failure is creating a client or page inside a loop and never closing it; another is correctly closing the page while an application collection still holds every screenshot.

Use try-with-resources where the API supports it

HtmlUnit’s getting-started guide models WebClient with try-with-resources and explains that the client owns browser state across page loads:

try (WebClient client = new WebClient(BrowserVersion.BEST_SUPPORTED)) {
    HtmlPage page = client.getPage("https://example.com");
    // render, capture, process, and release the result here
}

Use a current HtmlUnit version and close the WebClient, as its FAQ advises. Do not assume that this exact close sequence applies to every Playwright or Selenium version; follow the matching API documentation for browser, context, page, driver, and stream shutdown.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

HtmlUnit history is intentional state

The client can retain navigation history. If your workflow never uses back-navigation or history inspection, test the conditional reduction recommended by the FAQ:

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
client.getOptions().setHistoryPageCacheLimit(0);
client.getOptions().setHistorySizeLimit(0);

These settings reduce retained history; they are not a universal leak cure. Keep history enabled when the application needs it, and measure before and after.

3. Check whether screenshots, not browsers, fill the Java heap

Playwright Java’s in-memory screenshot API returns a byte[]; it can also save directly to a path. Selenium’s TakesScreenshot supports output such as a file or Base64 representation. Large arrays, Base64 expansion, repeated copies during encoding, or an unbounded result queue can therefore make the Java heap grow even when the browser is healthy. This is a data-retention problem to verify in your heap snapshots, not a claim that either API leaks.

Playwright Java

Prefer a path when downstream code does not need image bytes, and release any byte array as soon as processing finishes:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Path target = Path.of("shots", "page-" + index + ".png");
page.screenshot(new Page.ScreenshotOptions().setPath(target));

If you need bytes, process them synchronously and avoid storing every result:

byte[] image = page.screenshot(new Page.ScreenshotOptions()
    .setFullPage(false)
    .setScale("css"));
try {
    upload(image);
} finally {
    image = null;
}

Consult the Playwright Java Page API for the exact options available in your version. A null assignment is not a substitute for removing references from queues, caches, or closures.

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Selenium Java

Inspect the selected OutputType and the code that consumes it:

File file = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
try {
    Files.copy(file.toPath(), destination, StandardCopyOption.REPLACE_EXISTING);
} finally {
    // remove application references and delete temporary files when appropriate
}

The API also permits Base64 output. Avoid accumulating encoded strings, temporary files, or screenshot objects in a list unless that retention is intentional. See Selenium’s TakesScreenshot API.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

4. Reduce output size and page scope deliberately

A screenshot can become unexpectedly large because of page extent, device scale, or both. Playwright documents that device scale produces one image pixel per device pixel; a high-DPI setting can make an image twice as large or more than CSS scale. Full-page mode covers the entire scrollable page, not merely the viewport.

  • Use CSS scale when physical device pixels are not required.
  • Capture an element or viewport instead of the entire document when that satisfies the requirement.
  • Bound page dimensions or split very long pages when a single full-page image is unnecessary.
  • Choose PNG, JPEG, or another format according to fidelity and size needs; do not repeatedly convert between formats.

For syntax and behavior, see the Page API and the Playwright screenshots guide. These options control workload size; they do not by themselves prove or disprove a leak.

5. Separate Java growth from browser-side DOM and JavaScript growth

If Java heap is stable but the browser or renderer RSS climbs, investigate the page and browser process. Open tabs, contexts, event listeners, reachable JavaScript objects, and detached DOM trees can keep memory alive. Chrome’s guidance recommends Task Manager, memory/heap snapshots, and inspection of detached DOM trees and retained references; use Chrome DevTools’ memory-problems guide.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

Close pages, contexts, and browser instances at the intended scope. Reusing one context may be correct for a session, but it also deliberately preserves cookies, cache, and page state. Creating a fresh isolated context per job can control cross-page retention, at the cost of startup and resource overhead. Choose based on required state isolation and measure both variants.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

6. Treat hostile or pathological pages as a resource-control problem

Untrusted pages can consume memory through enormous documents, scripts, images, or request graphs even when your code releases objects correctly. HtmlUnit’s security guidance notes that parsing, DOM processing, JavaScript, and networking run inside the hosting JVM and recommends limits for time, memory, CPU, page size, and requests. Read HtmlUnit’s security details before rendering untrusted content.

  • Set navigation and script timeouts.
  • Restrict maximum page or response size where your library permits it.
  • Limit concurrent captures and bound work queues.
  • Block unnecessary resource types only when the resulting screenshot remains valid.
  • Run untrusted workloads in an isolated process or container when a JVM-wide failure is unacceptable.

7. A repeatable fix-and-verify procedure

  1. Baseline: run the same page mix and record heap, RSS, browser memory, dimensions, scale, and output-retention behavior.
  2. Prove the pool: compare two heap dumps if Java live objects grow; otherwise inspect native or browser metrics.
  3. Fix ownership: close the client/driver, context, page, streams, and temporary files at their documented boundaries.
  4. Remove accidental retention: bound queues and caches, stop collecting Base64 or byte arrays, and clear references after processing.
  5. Control image work: use CSS scale, element or viewport capture, and bounded full-page dimensions where acceptable.
  6. Control page state: for HtmlUnit, test zero history cache and size limits only when history is unnecessary; for automation browsers, choose deliberate context reuse or isolation.
  7. Re-run: compare post-warm-up retained sets under the same workload. A stable live set, not a perfectly flat instantaneous RSS graph, is the success criterion.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

8. Common symptoms and targeted fixes

Symptom Likely area What to check
Java used heap rises after each GC Application or JVM heap Heap dumps, GC roots, screenshot arrays, Base64 strings, queues, page/client objects
Heap is stable but RSS rises Native JVM or browser process Native-memory data and browser process metrics; do not rely on a Java heap dump alone
Only long pages cause growth Image dimensions or full-page scope Full-page extent, device scale, image format, and whether output is copied
Growth occurs only with HtmlUnit navigation Client state/history Current version, closed WebClient, and conditional history limits
Growth follows queue depth Application retention Consumer speed, bounded queue capacity, and references held after upload
Browser memory grows while Java remains flat DOM/JavaScript or open browser state DevTools heap snapshots, detached DOM trees, listeners, pages, and contexts

Or skip the browser setup

ScreenshotNeo is a website screenshot API and MCP server. It removes cookie-consent banners, newsletter popups, and chat widgets before capture; bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP tools—take_screenshot, get_page_info, and capture_pdf—let Claude, Cursor, or another MCP client capture pages without you managing a browser process.

One GET request returns PNG, JPEG, WebP, or PDF. The parameter set covers full-page and CSS-selector captures, dark mode, 12 device presets or custom viewports, retina scale, PDF paper and page options, custom CSS/JavaScript, clicks, waits, blocked resources, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, chosen cache TTLs, signed links, asynchronous webhooks, bulk capture of up to 100 URLs per call, usage reporting, and an OpenAPI specification. Existing parameter names used by other screenshot APIs also work, easing migration.

Use the ScreenshotNeo documentation for authentication and option details. The following calls are complete starting points:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

The Free plan includes 1,000 screenshots each month with no card. Paid plans start at $5 for 3,000 shots; every feature is on every plan, and annual billing provides two months free. Create a free ScreenshotNeo account to try it.

Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Frequently Asked Questions

Does a larger Java heap fix screenshot memory growth?

Only when profiling shows the workload needs more capacity and the live set is stable. A heap increase does not release retained objects or browser processes.

Should I force System.gc() after every screenshot?

No. Forced collections can distort performance and cannot collect objects that remain reachable. Use comparable GC points for diagnosis, then remove the references that retain results or page state.

Can a heap dump diagnose Chrome renderer memory?

No. A heap dump describes Java objects. Inspect the browser and renderer with their operating-system metrics and browser memory tools.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When should I disable HtmlUnit history?

Only when back-navigation and history inspection are not required. Test both history limits at zero and verify that the resulting workflow still behaves correctly.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.