0
# Asynchronous Execution
1
2
Callback-based asynchronous execution with dispatcher configuration and call management.
3
4
## Capabilities
5
6
### Callback
7
8
Callback for asynchronous HTTP calls with success and failure handling.
9
10
```java { .api }
11
public interface Callback {
12
void onFailure(Request request, IOException e);
13
void onResponse(Response response) throws IOException;
14
}
15
```
16
17
**Usage Examples:**
18
19
```java
20
// Simple callback implementation
21
Callback simpleCallback = new Callback() {
22
@Override
23
public void onFailure(Request request, IOException e) {
24
System.err.println("Request to " + request.url() + " failed: " + e.getMessage());
25
// Handle error - retry, notify user, etc.
26
}
27
28
@Override
29
public void onResponse(Response response) throws IOException {
30
try {
31
if (response.isSuccessful()) {
32
String responseData = response.body().string();
33
System.out.println("Success: " + responseData);
34
// Process successful response
35
} else {
36
System.err.println("HTTP error: " + response.code() + " " + response.message());
37
// Handle HTTP error codes
38
}
39
} finally {
40
response.body().close();
41
}
42
}
43
};
44
```
45
46
### Call
47
48
Represents a prepared HTTP request that can be executed synchronously or asynchronously.
49
50
```java { .api }
51
public final class Call {
52
public Response execute() throws IOException;
53
public void enqueue(Callback responseCallback);
54
public void cancel();
55
public boolean isExecuted();
56
public boolean isCanceled();
57
}
58
```
59
60
**Usage Examples:**
61
62
```java
63
// Asynchronous execution
64
Request request = new Request.Builder()
65
.url("https://api.example.com/data")
66
.build();
67
68
Call call = client.newCall(request);
69
call.enqueue(new Callback() {
70
@Override
71
public void onFailure(Request request, IOException e) {
72
System.err.println("Request failed: " + e.getMessage());
73
}
74
75
@Override
76
public void onResponse(Response response) throws IOException {
77
try {
78
if (response.isSuccessful()) {
79
String responseData = response.body().string();
80
System.out.println("Response: " + responseData);
81
} else {
82
System.err.println("Request failed: " + response.code());
83
}
84
} finally {
85
response.body().close();
86
}
87
}
88
});
89
90
// Call management
91
if (!call.isExecuted()) {
92
call.cancel(); // Cancel if not yet executed
93
}
94
95
// Check call state
96
boolean executed = call.isExecuted();
97
boolean canceled = call.isCanceled();
98
```
99
100
### Dispatcher
101
102
Manages execution of asynchronous HTTP calls with configurable limits and thread pooling.
103
104
```java { .api }
105
public final class Dispatcher {
106
public Dispatcher();
107
public Dispatcher(ExecutorService executorService);
108
public void setMaxRequests(int maxRequests);
109
public int getMaxRequests();
110
public void setMaxRequestsPerHost(int maxRequestsPerHost);
111
public int getMaxRequestsPerHost();
112
public void setIdleCallback(Runnable idleCallback);
113
public ExecutorService getExecutorService();
114
public void cancel(Object tag);
115
public int getRunningCallCount();
116
public int getQueuedCallCount();
117
}
118
```
119
120
**Usage Examples:**
121
122
```java
123
// Create custom dispatcher
124
Dispatcher dispatcher = new Dispatcher();
125
dispatcher.setMaxRequests(50); // Max concurrent requests
126
dispatcher.setMaxRequestsPerHost(5); // Max concurrent requests per host
127
128
// Apply to client
129
OkHttpClient client = new OkHttpClient();
130
client.setDispatcher(dispatcher);
131
132
// Monitor dispatcher state
133
System.out.println("Running calls: " + dispatcher.getRunningCallCount());
134
System.out.println("Queued calls: " + dispatcher.getQueuedCallCount());
135
136
// Cancel calls by tag
137
client.cancel("user-requests");
138
139
// Custom thread pool
140
ExecutorService customExecutor = Executors.newFixedThreadPool(10);
141
Dispatcher customDispatcher = new Dispatcher(customExecutor);
142
client.setDispatcher(customDispatcher);
143
```
144
145
### Dispatcher Configuration
146
147
Configure limits and behavior for asynchronous request execution.
148
149
```java { .api }
150
/**
151
* Set the maximum number of requests to execute concurrently.
152
* @param maxRequests the maximum concurrent requests (default: 64)
153
*/
154
public void setMaxRequests(int maxRequests);
155
156
/**
157
* Set the maximum number of requests for each host to execute concurrently.
158
* @param maxRequestsPerHost the maximum concurrent requests per host (default: 5)
159
*/
160
public void setMaxRequestsPerHost(int maxRequestsPerHost);
161
162
/**
163
* Set a callback to be executed when this dispatcher becomes idle.
164
* @param idleCallback callback to run when no calls are running or queued
165
*/
166
public void setIdleCallback(Runnable idleCallback);
167
168
/**
169
* Cancel all calls tagged with tag.
170
* @param tag the tag to match for cancellation
171
*/
172
public void cancel(Object tag);
173
```
174
175
**Usage Examples:**
176
177
```java
178
// Configure dispatcher limits
179
Dispatcher dispatcher = new Dispatcher();
180
dispatcher.setMaxRequests(100); // Allow up to 100 concurrent requests
181
dispatcher.setMaxRequestsPerHost(10); // Allow up to 10 per host
182
183
// Set idle callback for cleanup
184
dispatcher.setIdleCallback(new Runnable() {
185
@Override
186
public void run() {
187
System.out.println("Dispatcher is idle - all requests completed");
188
// Perform cleanup, send notifications, etc.
189
}
190
});
191
192
// Tag requests for group cancellation
193
Request request1 = new Request.Builder()
194
.url("https://api.example.com/data1")
195
.tag("batch-1")
196
.build();
197
198
Request request2 = new Request.Builder()
199
.url("https://api.example.com/data2")
200
.tag("batch-1")
201
.build();
202
203
// Later, cancel all requests with tag "batch-1"
204
dispatcher.cancel("batch-1");
205
```
206
207
### Monitoring Asynchronous Execution
208
209
Monitor the state and progress of asynchronous operations.
210
211
```java { .api }
212
/**
213
* Returns the number of running calls.
214
* @return count of currently executing calls
215
*/
216
public int getRunningCallCount();
217
218
/**
219
* Returns the number of calls awaiting execution.
220
* @return count of queued calls waiting to execute
221
*/
222
public int getQueuedCallCount();
223
```
224
225
**Usage Examples:**
226
227
```java
228
// Monitor dispatcher load
229
Dispatcher dispatcher = client.getDispatcher();
230
231
// Check if system is busy
232
if (dispatcher.getRunningCallCount() > 20) {
233
System.out.println("System busy, consider throttling new requests");
234
}
235
236
// Wait for all calls to complete
237
while (dispatcher.getRunningCallCount() > 0 || dispatcher.getQueuedCallCount() > 0) {
238
try {
239
Thread.sleep(100);
240
} catch (InterruptedException e) {
241
Thread.currentThread().interrupt();
242
break;
243
}
244
}
245
246
// Periodic monitoring
247
Timer monitor = new Timer();
248
monitor.scheduleAtFixedRate(new TimerTask() {
249
@Override
250
public void run() {
251
System.out.printf("Running: %d, Queued: %d%n",
252
dispatcher.getRunningCallCount(),
253
dispatcher.getQueuedCallCount());
254
}
255
}, 0, 5000); // Every 5 seconds
256
```