JAX-RS ChunkedOutput and ChunkedInput Example

In Jersey you can use ChunkedOutput to send response to a client in chunks. By using a chunked output the jersey runtime is informed that the response will be chunked and that the processing works asynchronously in a non-blocking fashion.


In the following example we return a ChunkedOutput instance. This informs Jersey that the response will be asynchronously processed. Usually, a long running method will be executed and as soon the method returns, the response will be sent to the client.

package com.memorynotfound.jaxrs.chunked;

import org.glassfish.jersey.server.ChunkedOutput;
import javax.ws.rs.*;
import java.io.*;

public class NumbersResource {

    public ChunkedOutput<String> streamExample(){
        final ChunkedOutput<String> output = new ChunkedOutput<String>(String.class);

        new Thread() {
            public void run() {
                try {
                    for (int i = 0; i < 100000 ; i++){
                        output.write(i + " ");
                } catch (IOException e){
                } finally {
                    try {
                    } catch (IOException e){
        return output;



On the client side, we use the ChunkedInput to receive chunked messages. The following example shows how to read from ChunkedInput.

package com.memorynotfound.jaxrs.chunked;

import org.glassfish.jersey.client.ChunkedInput;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.Response;

public class RunClient {

    public static void main(String... args){
        Client client = ClientBuilder.newClient();

        Response response = client

        ChunkedInput<String> input = response.readEntity(new GenericType<ChunkedInput<String>>() {});

        String chunk;
        while ((chunk = input.read()) != null){
            System.out.println("chunk: " + chunk);



You may also like...