CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-com-squareup-okhttp--okhttp

An HTTP & SPDY client for Android and Java applications with efficient connection pooling, interceptors, and modern protocol support

Pending
Overview
Eval results
Files

async-execution.mddocs/

Asynchronous Execution

Callback-based asynchronous execution with dispatcher configuration and call management.

Capabilities

Callback

Callback for asynchronous HTTP calls with success and failure handling.

public interface Callback {
    void onFailure(Request request, IOException e);
    void onResponse(Response response) throws IOException;
}

Usage Examples:

// Simple callback implementation
Callback simpleCallback = new Callback() {
    @Override
    public void onFailure(Request request, IOException e) {
        System.err.println("Request to " + request.url() + " failed: " + e.getMessage());
        // Handle error - retry, notify user, etc.
    }
    
    @Override
    public void onResponse(Response response) throws IOException {
        try {
            if (response.isSuccessful()) {
                String responseData = response.body().string();
                System.out.println("Success: " + responseData);
                // Process successful response
            } else {
                System.err.println("HTTP error: " + response.code() + " " + response.message());
                // Handle HTTP error codes
            }
        } finally {
            response.body().close();
        }
    }
};

Call

Represents a prepared HTTP request that can be executed synchronously or asynchronously.

public final class Call {
    public Response execute() throws IOException;
    public void enqueue(Callback responseCallback);
    public void cancel();
    public boolean isExecuted();
    public boolean isCanceled();
}

Usage Examples:

// Asynchronous execution
Request request = new Request.Builder()
    .url("https://api.example.com/data")
    .build();

Call call = client.newCall(request);
call.enqueue(new Callback() {
    @Override
    public void onFailure(Request request, IOException e) {
        System.err.println("Request failed: " + e.getMessage());
    }
    
    @Override
    public void onResponse(Response response) throws IOException {
        try {
            if (response.isSuccessful()) {
                String responseData = response.body().string();
                System.out.println("Response: " + responseData);
            } else {
                System.err.println("Request failed: " + response.code());
            }
        } finally {
            response.body().close();
        }
    }
});

// Call management
if (!call.isExecuted()) {
    call.cancel(); // Cancel if not yet executed
}

// Check call state
boolean executed = call.isExecuted();
boolean canceled = call.isCanceled();

Dispatcher

Manages execution of asynchronous HTTP calls with configurable limits and thread pooling.

public final class Dispatcher {
    public Dispatcher();
    public Dispatcher(ExecutorService executorService);
    public void setMaxRequests(int maxRequests);
    public int getMaxRequests();
    public void setMaxRequestsPerHost(int maxRequestsPerHost);
    public int getMaxRequestsPerHost();
    public void setIdleCallback(Runnable idleCallback);
    public ExecutorService getExecutorService();
    public void cancel(Object tag);
    public int getRunningCallCount();
    public int getQueuedCallCount();
}

Usage Examples:

// Create custom dispatcher
Dispatcher dispatcher = new Dispatcher();
dispatcher.setMaxRequests(50);           // Max concurrent requests
dispatcher.setMaxRequestsPerHost(5);     // Max concurrent requests per host

// Apply to client
OkHttpClient client = new OkHttpClient();
client.setDispatcher(dispatcher);

// Monitor dispatcher state
System.out.println("Running calls: " + dispatcher.getRunningCallCount());
System.out.println("Queued calls: " + dispatcher.getQueuedCallCount());

// Cancel calls by tag
client.cancel("user-requests");

// Custom thread pool
ExecutorService customExecutor = Executors.newFixedThreadPool(10);
Dispatcher customDispatcher = new Dispatcher(customExecutor);
client.setDispatcher(customDispatcher);

Dispatcher Configuration

Configure limits and behavior for asynchronous request execution.

/**
 * Set the maximum number of requests to execute concurrently.
 * @param maxRequests the maximum concurrent requests (default: 64)
 */
public void setMaxRequests(int maxRequests);

/**
 * Set the maximum number of requests for each host to execute concurrently.
 * @param maxRequestsPerHost the maximum concurrent requests per host (default: 5)
 */
public void setMaxRequestsPerHost(int maxRequestsPerHost);

/**
 * Set a callback to be executed when this dispatcher becomes idle.
 * @param idleCallback callback to run when no calls are running or queued
 */
public void setIdleCallback(Runnable idleCallback);

/**
 * Cancel all calls tagged with tag.
 * @param tag the tag to match for cancellation
 */
public void cancel(Object tag);

Usage Examples:

// Configure dispatcher limits
Dispatcher dispatcher = new Dispatcher();
dispatcher.setMaxRequests(100);         // Allow up to 100 concurrent requests
dispatcher.setMaxRequestsPerHost(10);   // Allow up to 10 per host

// Set idle callback for cleanup
dispatcher.setIdleCallback(new Runnable() {
    @Override
    public void run() {
        System.out.println("Dispatcher is idle - all requests completed");
        // Perform cleanup, send notifications, etc.
    }
});

// Tag requests for group cancellation
Request request1 = new Request.Builder()
    .url("https://api.example.com/data1")
    .tag("batch-1")
    .build();

Request request2 = new Request.Builder()
    .url("https://api.example.com/data2")
    .tag("batch-1")
    .build();

// Later, cancel all requests with tag "batch-1"
dispatcher.cancel("batch-1");

Monitoring Asynchronous Execution

Monitor the state and progress of asynchronous operations.

/**
 * Returns the number of running calls.
 * @return count of currently executing calls
 */
public int getRunningCallCount();

/**
 * Returns the number of calls awaiting execution.
 * @return count of queued calls waiting to execute
 */
public int getQueuedCallCount();

Usage Examples:

// Monitor dispatcher load
Dispatcher dispatcher = client.getDispatcher();

// Check if system is busy
if (dispatcher.getRunningCallCount() > 20) {
    System.out.println("System busy, consider throttling new requests");
}

// Wait for all calls to complete
while (dispatcher.getRunningCallCount() > 0 || dispatcher.getQueuedCallCount() > 0) {
    try {
        Thread.sleep(100);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        break;
    }
}

// Periodic monitoring
Timer monitor = new Timer();
monitor.scheduleAtFixedRate(new TimerTask() {
    @Override
    public void run() {
        System.out.printf("Running: %d, Queued: %d%n", 
            dispatcher.getRunningCallCount(),
            dispatcher.getQueuedCallCount());
    }
}, 0, 5000); // Every 5 seconds

Install with Tessl CLI

npx tessl i tessl/maven-com-squareup-okhttp--okhttp

docs

async-execution.md

authentication-security.md

caching.md

connection-management.md

form-data-multipart.md

http-client.md

http-utilities.md

index.md

interceptors.md

request-building.md

request-response-bodies.md

response-handling.md

tile.json