Revised 16 November 2026 for Java 25 and Quarkus 3.40.1.2. The original article URL is unchanged.
I have always loved the look of old video games. The chunky pixels, imperfect shading, and the illusion of detail created by dithering on limited hardware give even a small image its own character. The original idea for this service was to take a modern image and generate that retro look with a few Java filters.
The same application gives us a concrete way to discuss virtual threads. A request reads an uploaded image, changes its pixels, and writes a PNG response. Reading and writing involve I/O, but decoding, dithering, and encoding also consume CPU. Putting the endpoint on a virtual thread moves it away from the event loop. It does not make those calculations faster or isolate them on a separate CPU executor.
We'll keep the three-filter design and make the resource limits explicit. The revised service checks image dimensions before decoding and admits only two conversions at a time. That gives us a small application you can run and inspect without treating the number of virtual threads as a substitute for a memory budget.
Get the application running
Use JDK 25 and set JAVA_HOME to that installation. The companion uses Quarkus 3.40.1.2 and includes the Maven wrapper, so the first invocation downloads Maven and the dependencies. No database, broker, or container is needed for the local application.
The maintained companion is in the new repository:
git clone https://github.com/myfear/the-main-thread.git
cd the-main-thread/pixel-art-converter
./mvnw quarkus:dev
If you already cloned the repository, update that checkout and enter pixel-art-converter. Keep the application terminal open. In another terminal, send a local PNG or JPEG, replacing photo.jpg with your file:
curl --fail-with-body -sS \
-F 'image=@photo.jpg' \
-F 'blockSize=8' \
http://localhost:8080/api/filter/pixelate \
-o pixelated.png
Open the resulting PNG. A larger blockSize produces larger visible pixels. The default is 8, and the service accepts values up to 128 when they fit inside both image dimensions. We'll follow that request through the filters and then look at the checks around them.
The complete source is in the companion. The code below follows those files; you can read it alongside the running application. The original Java 21 edition is available as a historical reference.
Keep each filter independent
The filters use ordinary Java classes and accept a BufferedImage. The interface in src/main/java/com/pixel/filter/ImageFilter.java makes each transformation interchangeable:
package com.pixel.filter;
import java.awt.image.BufferedImage;
public interface ImageFilter {
BufferedImage apply(BufferedImage image);
String getName();
}
Each implementation creates a new image. That lets the chain pass one result to the next filter while leaving the caller's input unchanged. The service class holds no image state between requests:
public BufferedImage applyChain(BufferedImage input, List<ImageFilter> filters) {
BufferedImage current = input;
for (ImageFilter f : filters) {
current = f.apply(current);
}
return current;
}
The request uses a downsample filter, a dithering filter, and an upsample filter in that order. The factory translates the filter descriptions into instances. These classes don't need their own threads: the caller executes the chain sequentially, and the order changes the result.
Reduce the image before dithering
DownsampleFilter chooses the top-left pixel of each block. Here is its apply method:
@Override
public BufferedImage apply(BufferedImage img) {
int w = Math.max(1, img.getWidth() / blockSize);
int h = Math.max(1, img.getHeight() / blockSize);
BufferedImage result = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
int rgb = img.getRGB(x * blockSize, y * blockSize);
result.setRGB(x, y, rgb);
}
}
return result;
}
With block size 8, an image 53 pixels wide becomes 6 pixels wide at this stage. The integer division discards the incomplete block at the right edge. The same happens at the bottom edge for height. After upscaling, that 53 × 37 source becomes 48 × 32 pixels. This is a deliberate consequence of the original algorithm, so the API returns the final dimensions in response headers.
The endpoint rejects a block size larger than either source dimension. That prevents a tiny source from being expanded through the Math.max(1, ...) fallback. The helper's behavior is convenient for an isolated filter, while the HTTP endpoint imposes the stricter contract readers can rely on.
Spread quantization error
The Floyd–Steinberg filter reduces each color channel to a restricted set of values, then passes the rounding error to nearby pixels. A region can alternate between neighboring shades and preserve the impression of a value that the reduced palette cannot represent directly.
Our implementation rounds using a step of 32. That produces channel values of 0, 32, 64, 96, 128, 160, 192, 224, and 255 after clamping. The number 32 is the spacing used for quantization; it does not mean the output has 32 distinct levels per channel.
The central calculation in FloydSteinbergFilter.java is:
int factor = 32;
int newR = Math.round(factor * Math.round(oldR / (float) factor));
int newG = Math.round(factor * Math.round(oldG / (float) factor));
int newB = Math.round(factor * Math.round(oldB / (float) factor));
newR = Math.min(255, Math.max(0, newR));
newG = Math.min(255, Math.max(0, newG));
newB = Math.min(255, Math.max(0, newB));
For each pixel, the filter distributes error to the next pixel on the right with weight 7/16. On the following row, it distributes error to the left, center, and right neighbors with weights 3/16, 5/16, and 1/16. It processes pixels from left to right and top to bottom, so the affected neighbors have not been quantized yet.
The complete filter implementation keeps an integer buffer for all three channels and checks image boundaries when distributing error. This buffer consumes memory in addition to the source and output images. Downsampling first reduces its size substantially when blockSize is greater than one. At block size one, that reduction does not happen, which is one reason the service also limits the source pixel count.
Restore the visible pixel size
The final filter expands the smaller image using nearest-neighbor interpolation:
@Override
public BufferedImage apply(BufferedImage img) {
int w = img.getWidth() * scale;
int h = img.getHeight() * scale;
BufferedImage result = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g = result.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
g.drawImage(img, 0, 0, w, h, null);
g.dispose();
return result;
}
Nearest-neighbor interpolation preserves the hard edges we want. A smoothing interpolation would blend those edges and change the retro effect. The endpoint uses the same value for downsampling and upscaling, so complete source blocks return to their original size.
This implementation uses RGB images. PNG transparency is discarded, and JPEG EXIF orientation is not applied. Accept PNG and JPEG files whose orientation is already correct if you want the output to follow what you see in an image editor.
Admit a conversion before allocating its images
A compressed upload and a decoded image can have very different sizes. Limiting the HTTP body to 15 MiB does not tell us how much memory its raster, filter buffers, and PNG output will need. The configuration therefore includes separate limits:
quarkus.http.limits.max-body-size=15M
quarkus.http.limits.max-form-attribute-size=15M
pixel.max-concurrent=2
pixel.max-pixels=4000000
pixel.max-block-size=128
The request-size limit covers the entire multipart body, including overhead. The pixel limit checks source width multiplied by source height, using a long so the multiplication cannot overflow an integer. ImageDecoder asks an ImageReader for the format and dimensions before calling read(0). Unsupported formats are rejected, and an image with more than four million source pixels receives HTTP 413 before full raster decoding.
There is also a shared ConversionGate:
package com.pixel.service;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicBoolean;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.Response;
@ApplicationScoped
public class ConversionGate {
private final Semaphore slots;
public ConversionGate(ImageLimits limits) {
if (limits.maxConcurrent() < 1 || limits.maxPixels() < 1 || limits.maxBlockSize() < 1) {
throw new IllegalArgumentException("Image limits must be positive");
}
slots = new Semaphore(limits.maxConcurrent());
}
public Permit enter() {
if (!slots.tryAcquire()) {
throw new WebApplicationException(Response.status(503).header("Retry-After", "1").build());
}
return new Permit();
}
public final class Permit implements AutoCloseable {
private final AtomicBoolean released = new AtomicBoolean();
@Override
public void close() {
if (released.compareAndSet(false, true)) {
slots.release();
}
}
}
}
tryAcquire() either reserves a slot immediately or returns false. We don't queue another conversion inside this gate. A full gate produces HTTP 503 and a Retry-After: 1 header, which tells a caller it can try later. The permit is closed in a try-with-resources block around decoding, filtering, and encoding, so failures release capacity too. Its idempotent close() prevents an accidental double close from increasing the semaphore's capacity.
The limit applies per application instance. Multipart upload handling happens before the resource method, so the gate does not limit open connections or temporary upload storage. It bounds active conversions that hold decoded images. Set the count and pixel limit according to the heap and CPU available to your application; neither value is a promise about total process memory.
Follow the virtual-thread endpoint
ImageFilterResource receives its services through constructor injection. The request method performs inexpensive parameter checks before entering the gate:
@POST
@Path("/pixelate")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces("image/png")
@RunOnVirtualThread
public Response pixelate(@RestForm("image") FileUpload image,
@RestForm("blockSize") @DefaultValue("8") int blockSize) {
if (image == null || image.size() == 0) {
throw new BadRequestException("A nonempty image is required");
}
if (blockSize < 1 || blockSize > limits.maxBlockSize()) {
throw new BadRequestException("blockSize must be between 1 and " + limits.maxBlockSize());
}
try (var permit = gate.enter()) {
var source = decoder.read(image.uploadedFile(), blockSize);
var result = chain.applyChain(source, factory.createChain(List.of(
new FilterConfigDTO("downsample", Map.of("blockSize", blockSize)),
new FilterConfigDTO("dither", Map.of()),
new FilterConfigDTO("upsample", Map.of("scale", blockSize)))));
try (var output = new ByteArrayOutputStream()) {
if (!ImageIO.write(result, "PNG", output)) {
throw new IOException("PNG writer unavailable");
}
return Response.ok(output.toByteArray())
.header("X-Execution-Virtual", Thread.currentThread().isVirtual())
.header("X-Image-Width", result.getWidth())
.header("X-Image-Height", result.getHeight()).build();
} catch (IOException e) {
LOG.error("PNG encoding failed", e);
throw new InternalServerErrorException("PNG encoding failed");
}
}
}
The @RunOnVirtualThread annotation tells Quarkus to invoke this blocking REST method on a virtual thread. There is no separate enablement property to add. A successful response includes X-Execution-Virtual: true, so you can inspect the execution choice directly with curl -D headers.txt.
Everything inside the gate executes sequentially on that request thread. The filter loops and PNG compression occupy its carrier while they calculate. Some I/O operations may release a carrier while waiting, but you cannot assume every ImageIO or filesystem operation does so. The annotation protects the event loop from executing this method; it does not create a separate pool for image calculations.
For a service dominated by sustained image conversion, compare ordinary worker execution and a bounded CPU executor before selecting a deployment model. A dedicated executor also needs a bounded queue, explicit rejection, and a defined shutdown lifecycle. This companion retains the virtual-thread endpoint to make its behavior visible, with an admission limit that prevents an unbounded number of simultaneous conversions. It does not claim a throughput advantage over worker threads.
Check failures as well as the picture
An image endpoint needs more than a successful file download. The service returns 400 for invalid block sizes, missing uploads, unsupported formats, and images that cannot be decoded. Oversized multipart bodies and decoded pixel counts return 413. When all conversion slots are occupied, it returns 503. Application errors use a JSON error field; HTTP-layer rejection can use the framework's own error representation.
Try an invalid block size:
curl -i -F 'image=@photo.jpg' -F 'blockSize=0' \
http://localhost:8080/api/filter/pixelate
You should receive 400. Using --fail-with-body in the download command also makes curl report HTTP errors instead of quietly treating the error body as a successful PNG.
The tests generate their input images in Java. Filter tests check selected source pixels, nearest-neighbor repetition, palette values, and preservation of the input. HTTP tests decode the returned PNG and check its dimensions. Other tests exercise invalid input, request and pixel limits, a full conversion gate, and capacity release after exceptions. The dithering test uses a constant shade of 140 and expects output shades of 128 and 160, which tests a specific consequence of error diffusion.
Stop dev mode and run:
./mvnw verify -DskipITs=false
The integration suite repeats the HTTP checks against the packaged JVM application. Start that application with:
java -Djava.awt.headless=true -jar target/quarkus-app/quarkus-run.jar
Headless mode allows AWT image operations without a display. This companion validates JVM execution. Native-image support for AWT and image codecs would require a separate build and runtime check, so the README does not present a native build as a tested path.
Java versions and the next step
Java 24 removed the monitor-related pinning associated with synchronized, and Java 25 includes that change. It does not remove the CPU cost of the filter loops. The Quarkus virtual-thread reference covers pinning tests and carrier monopolization; the general tutorial shows request dispatch and concurrent subtasks separately.
Quarkus 4 raises its Java baseline to 21. This example targets Quarkus 3.40.1.2 on Java 25, so its compatibility claims stop there. Changing the framework version is a separate check from understanding which parts of a request wait and which parts calculate.
The three filters give us the retro image that motivated the service, and the limits give each conversion a defined share of the application's capacity. When you adapt the example, keep those two aspects connected: increasing image dimensions changes allocation and computation, while allowing more concurrent requests multiplies both. Choose those limits from the resources you can afford, then measure the service with the images and traffic it will actually receive.



