0
# Session Management
1
2
MINA Core provides comprehensive session management through the `IoSession` interface and related components. Sessions represent connections between endpoints and provide lifecycle management, configuration, and attribute storage.
3
4
## Core Interfaces
5
6
### IoSessionAttributeMap
7
8
Interface for pluggable attribute storage implementations:
9
10
```java { .api }
11
public interface IoSessionAttributeMap {
12
Object getAttribute(IoSession session, Object key, Object defaultValue);
13
Object setAttribute(IoSession session, Object key, Object value);
14
Object setAttributeIfAbsent(IoSession session, Object key, Object value);
15
Object removeAttribute(IoSession session, Object key);
16
boolean removeAttribute(IoSession session, Object key, Object value);
17
boolean replaceAttribute(IoSession session, Object key, Object oldValue, Object newValue);
18
boolean containsAttribute(IoSession session, Object key);
19
Set<Object> getAttributeKeys(IoSession session);
20
void dispose(IoSession session) throws Exception;
21
}
22
```
23
24
### IoSessionDataStructureFactory
25
26
Factory for creating session data structures:
27
28
```java { .api }
29
public interface IoSessionDataStructureFactory {
30
IoSessionAttributeMap getAttributeMap(IoSession session) throws Exception;
31
WriteRequestQueue getWriteRequestQueue(IoSession session) throws Exception;
32
}
33
```
34
35
### IoSessionRecycler
36
37
Interface for session recycling in connectionless transports:
38
39
```java { .api }
40
public interface IoSessionRecycler {
41
void put(IoSession session);
42
IoSession recycle(SocketAddress localAddress, SocketAddress remoteAddress);
43
void remove(IoSession session);
44
}
45
```
46
47
### IoSessionInitializationException
48
49
Exception thrown during session initialization:
50
51
```java { .api }
52
public class IoSessionInitializationException extends RuntimeException {
53
public IoSessionInitializationException();
54
public IoSessionInitializationException(String message);
55
public IoSessionInitializationException(String message, Throwable cause);
56
public IoSessionInitializationException(Throwable cause);
57
}
58
```
59
60
### IoSession
61
62
The central interface representing a connection between two endpoints:
63
64
```java { .api }
65
public interface IoSession {
66
// Identity and metadata
67
long getId();
68
IoService getService();
69
IoHandler getHandler();
70
TransportMetadata getTransportMetadata();
71
72
// Configuration and state
73
IoSessionConfig getConfig();
74
boolean isConnected();
75
boolean isActive();
76
boolean isClosing();
77
boolean isSecured();
78
boolean isServer();
79
80
// Address information
81
SocketAddress getRemoteAddress();
82
SocketAddress getLocalAddress();
83
SocketAddress getServiceAddress();
84
85
// I/O operations
86
WriteFuture write(Object message);
87
WriteFuture write(Object message, SocketAddress destination);
88
ReadFuture read();
89
90
// Session closure
91
CloseFuture closeNow();
92
CloseFuture closeOnFlush();
93
CloseFuture getCloseFuture();
94
95
// Attribute management
96
Object getAttribute(Object key);
97
Object getAttribute(Object key, Object defaultValue);
98
Object setAttribute(Object key, Object value);
99
Object setAttribute(Object key);
100
Object setAttributeIfAbsent(Object key, Object value);
101
Object setAttributeIfAbsent(Object key);
102
Object removeAttribute(Object key);
103
boolean removeAttribute(Object key, Object value);
104
boolean replaceAttribute(Object key, Object oldValue, Object newValue);
105
boolean containsAttribute(Object key);
106
Set<Object> getAttributeKeys();
107
108
// Flow control
109
void suspendRead();
110
void suspendWrite();
111
void resumeRead();
112
void resumeWrite();
113
boolean isReadSuspended();
114
boolean isWriteSuspended();
115
116
// Filter chain and write queue access
117
IoFilterChain getFilterChain();
118
WriteRequestQueue getWriteRequestQueue();
119
void setCurrentWriteRequest(WriteRequest currentWriteRequest);
120
121
// Extended statistics and timing
122
long getCreationTime();
123
long getLastIoTime();
124
long getLastReadTime();
125
long getLastWriteTime();
126
long getReadBytes();
127
long getWrittenBytes();
128
long getReadMessages();
129
long getWrittenMessages();
130
double getReadBytesThroughput();
131
double getWrittenBytesThroughput();
132
double getReadMessagesThroughput();
133
double getWrittenMessagesThroughput();
134
int getScheduledWriteMessages();
135
long getScheduledWriteBytes();
136
Object getCurrentWriteMessage();
137
WriteRequest getCurrentWriteRequest();
138
139
// Extended idle detection
140
boolean isIdle(IdleStatus status);
141
boolean isReaderIdle();
142
boolean isWriterIdle();
143
boolean isBothIdle();
144
int getIdleCount(IdleStatus status);
145
int getReaderIdleCount();
146
int getWriterIdleCount();
147
int getBothIdleCount();
148
long getLastIdleTime(IdleStatus status);
149
long getLastReaderIdleTime();
150
long getLastWriterIdleTime();
151
long getLastBothIdleTime();
152
153
// Throughput calculation
154
void updateThroughput(long currentTime, boolean force);
155
}
156
```
157
158
### IoSessionConfig
159
160
Configuration interface for session-specific settings:
161
162
```java { .api }
163
public interface IoSessionConfig {
164
// Buffer sizes
165
int getReadBufferSize();
166
void setReadBufferSize(int readBufferSize);
167
int getMinReadBufferSize();
168
void setMinReadBufferSize(int minReadBufferSize);
169
int getMaxReadBufferSize();
170
void setMaxReadBufferSize(int maxReadBufferSize);
171
172
// Idle time configuration
173
int getIdleTime(IdleStatus status);
174
void setIdleTime(IdleStatus status, int idleTime);
175
int getReaderIdleTime();
176
void setReaderIdleTime(int idleTimeInSeconds);
177
int getWriterIdleTime();
178
void setWriterIdleTime(int idleTimeInSeconds);
179
int getBothIdleTime();
180
void setBothIdleTime(int idleTimeInSeconds);
181
182
// Throughput calculation
183
int getThroughputCalculationInterval();
184
void setThroughputCalculationInterval(int throughputCalculationInterval);
185
186
// Write timeout
187
int getWriteTimeout();
188
void setWriteTimeout(int writeTimeout);
189
long getWriteTimeoutInMillis();
190
191
// Extended idle time methods
192
long getIdleTimeInMillis(IdleStatus status);
193
long getReaderIdleTimeInMillis();
194
long getWriterIdleTimeInMillis();
195
long getBothIdleTimeInMillis();
196
197
// Extended throughput methods
198
long getThroughputCalculationIntervalInMillis();
199
200
// Read operation
201
boolean isUseReadOperation();
202
void setUseReadOperation(boolean useReadOperation);
203
204
// Configuration copy
205
void setAll(IoSessionConfig config);
206
}
207
```
208
209
## Session Lifecycle
210
211
### Session States
212
213
Sessions progress through several states during their lifecycle:
214
215
```java { .api }
216
public enum SessionState {
217
OPENING, // Session is being established
218
OPENED, // Session is active and ready for I/O
219
CLOSING // Session is being closed
220
}
221
```
222
223
### Lifecycle Events
224
225
Handle session lifecycle events through IoHandler:
226
227
```java { .api }
228
public class SessionLifecycleHandler extends IoHandlerAdapter {
229
230
@Override
231
public void sessionCreated(IoSession session) throws Exception {
232
// Called when session is first created (before opening)
233
System.out.println("Session created: " + session.getId());
234
235
// Initialize session attributes
236
session.setAttribute("createTime", System.currentTimeMillis());
237
session.setAttribute("requestCount", 0);
238
}
239
240
@Override
241
public void sessionOpened(IoSession session) throws Exception {
242
// Called when session is opened and ready for I/O
243
System.out.println("Session opened: " + session.getRemoteAddress());
244
245
// Configure session-specific settings
246
IoSessionConfig config = session.getConfig();
247
config.setReadBufferSize(4096);
248
config.setIdleTime(IdleStatus.BOTH_IDLE, 300); // 5 minutes
249
config.setWriteTimeout(30); // 30 seconds
250
251
// Send welcome message
252
session.write("Welcome to the server!");
253
}
254
255
@Override
256
public void sessionClosed(IoSession session) throws Exception {
257
// Called when session is closed
258
Long createTime = (Long) session.getAttribute("createTime");
259
long duration = System.currentTimeMillis() - createTime;
260
System.out.println("Session closed after " + duration + "ms");
261
262
// Cleanup resources
263
cleanupSessionResources(session);
264
}
265
266
@Override
267
public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
268
// Called when session becomes idle
269
System.out.println("Session idle: " + status);
270
271
if (status == IdleStatus.BOTH_IDLE) {
272
// Close inactive sessions
273
session.closeNow();
274
} else if (status == IdleStatus.WRITER_IDLE) {
275
// Send keep-alive message
276
session.write("PING");
277
}
278
}
279
}
280
```
281
282
## Session Configuration
283
284
### Basic Configuration
285
286
```java { .api }
287
// Configure session settings during initialization
288
public void configureSession(IoSession session) {
289
IoSessionConfig config = session.getConfig();
290
291
// Buffer configuration
292
config.setReadBufferSize(8192); // 8KB read buffer
293
config.setMinReadBufferSize(1024); // Minimum 1KB
294
config.setMaxReadBufferSize(65536); // Maximum 64KB
295
296
// Idle timeout configuration (in seconds)
297
config.setIdleTime(IdleStatus.READER_IDLE, 60); // 1 minute read timeout
298
config.setIdleTime(IdleStatus.WRITER_IDLE, 30); // 30 seconds write timeout
299
config.setIdleTime(IdleStatus.BOTH_IDLE, 90); // 90 seconds total timeout
300
301
// Write timeout (in seconds)
302
config.setWriteTimeout(10);
303
304
// Throughput calculation interval (in seconds)
305
config.setThroughputCalculationInterval(3);
306
}
307
```
308
309
### Transport-Specific Configuration
310
311
```java { .api }
312
// TCP Socket configuration
313
public void configureTcpSession(IoSession session) {
314
if (session.getTransportMetadata().getProviderName().equals("nio")) {
315
// Access socket-specific configuration directly from the session
316
SocketSessionConfig config = (SocketSessionConfig) session.getConfig();
317
config.setSendBufferSize(64 * 1024); // 64KB send buffer
318
config.setReceiveBufferSize(64 * 1024); // 64KB receive buffer
319
config.setTcpNoDelay(true); // Disable Nagle algorithm
320
config.setKeepAlive(true); // Enable keep-alive
321
config.setSoLinger(0); // Immediate close
322
config.setReuseAddress(true); // Allow address reuse
323
}
324
}
325
```
326
327
## Session Attributes
328
329
### Type-Safe Attributes
330
331
Use `AttributeKey` for type-safe session attributes:
332
333
```java { .api }
334
// Define attribute keys
335
public class SessionAttributes {
336
public static final AttributeKey USER_INFO = new AttributeKey(UserInfo.class, "userInfo");
337
public static final AttributeKey LOGIN_TIME = new AttributeKey(Long.class, "loginTime");
338
public static final AttributeKey REQUEST_COUNT = new AttributeKey(Integer.class, "requestCount");
339
public static final AttributeKey SESSION_DATA = new AttributeKey(Map.class, "sessionData");
340
}
341
342
// Using type-safe attributes
343
public class TypeSafeSessionHandler extends IoHandlerAdapter {
344
345
@Override
346
public void sessionOpened(IoSession session) throws Exception {
347
// Set typed attributes
348
session.setAttribute(SessionAttributes.LOGIN_TIME, System.currentTimeMillis());
349
session.setAttribute(SessionAttributes.REQUEST_COUNT, 0);
350
session.setAttribute(SessionAttributes.SESSION_DATA, new HashMap<String, Object>());
351
}
352
353
@Override
354
public void messageReceived(IoSession session, Object message) throws Exception {
355
// Get typed attributes
356
Integer count = (Integer) session.getAttribute(SessionAttributes.REQUEST_COUNT);
357
session.setAttribute(SessionAttributes.REQUEST_COUNT, count + 1);
358
359
// Check if user is authenticated
360
UserInfo user = (UserInfo) session.getAttribute(SessionAttributes.USER_INFO);
361
if (user == null) {
362
session.write("Please authenticate first");
363
return;
364
}
365
366
// Process authenticated request
367
processRequest(session, user, message);
368
}
369
}
370
```
371
372
### Attribute Operations
373
374
```java { .api }
375
// Atomic attribute operations
376
public class AttributeOperations {
377
378
public void atomicIncrement(IoSession session, AttributeKey key) {
379
session.setAttribute(key, ((Integer) session.getAttribute(key, 0)) + 1);
380
}
381
382
public boolean setIfAbsent(IoSession session, AttributeKey key, Object value) {
383
return session.setAttributeIfAbsent(key, value) == null;
384
}
385
386
public boolean replaceValue(IoSession session, AttributeKey key,
387
Object oldValue, Object newValue) {
388
return session.replaceAttribute(key, oldValue, newValue);
389
}
390
391
public boolean removeValue(IoSession session, AttributeKey key, Object value) {
392
return session.removeAttribute(key, value);
393
}
394
}
395
```
396
397
## Idle Detection
398
399
### Idle Status Types
400
401
```java { .api }
402
public class IdleStatus {
403
public static final IdleStatus READER_IDLE = new IdleStatus("READER_IDLE");
404
public static final IdleStatus WRITER_IDLE = new IdleStatus("WRITER_IDLE");
405
public static final IdleStatus BOTH_IDLE = new IdleStatus("BOTH_IDLE");
406
407
private final String name;
408
409
private IdleStatus(String name) {
410
this.name = name;
411
}
412
413
@Override
414
public String toString() {
415
return name;
416
}
417
}
418
```
419
420
### Implementing Idle Detection
421
422
```java { .api }
423
public class IdleDetectionHandler extends IoHandlerAdapter {
424
425
@Override
426
public void sessionOpened(IoSession session) throws Exception {
427
// Configure idle detection
428
session.getConfig().setIdleTime(IdleStatus.READER_IDLE, 30); // 30 seconds
429
session.getConfig().setIdleTime(IdleStatus.WRITER_IDLE, 60); // 1 minute
430
session.getConfig().setIdleTime(IdleStatus.BOTH_IDLE, 120); // 2 minutes
431
}
432
433
@Override
434
public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
435
int idleCount = session.getIdleCount(status);
436
437
switch (status) {
438
case READER_IDLE:
439
if (idleCount >= 3) {
440
// Close session after 3 consecutive reader idle events
441
session.closeNow();
442
} else {
443
// Send keep-alive request
444
session.write("PING");
445
}
446
break;
447
448
case WRITER_IDLE:
449
// Send heartbeat to keep connection alive
450
session.write("HEARTBEAT");
451
break;
452
453
case BOTH_IDLE:
454
// Close completely idle sessions
455
System.out.println("Closing idle session: " + session.getId());
456
session.closeNow();
457
break;
458
}
459
}
460
}
461
```
462
463
## Flow Control
464
465
### Suspending and Resuming I/O
466
467
```java { .api }
468
public class FlowControlExample {
469
470
public void handleBackpressure(IoSession session) {
471
// Check write queue size
472
int queuedMessages = session.getScheduledWriteMessages();
473
long queuedBytes = session.getScheduledWriteBytes();
474
475
if (queuedMessages > 1000 || queuedBytes > 1024 * 1024) { // 1MB
476
// Suspend reading to apply backpressure
477
session.suspendRead();
478
479
// Schedule resume after delay
480
scheduleResumeRead(session, 1000); // 1 second delay
481
}
482
}
483
484
public void suspendSlowClient(IoSession session) {
485
// Check throughput
486
double writeThroughput = session.getWrittenBytesThroughput();
487
if (writeThroughput < 1024) { // Less than 1KB/s
488
// Suspend write operations for slow client
489
session.suspendWrite();
490
491
// Mark session for potential cleanup
492
session.setAttribute("suspended", true);
493
}
494
}
495
496
public void resumeOperations(IoSession session) {
497
if (session.isReadSuspended()) {
498
session.resumeRead();
499
}
500
501
if (session.isWriteSuspended()) {
502
session.resumeWrite();
503
session.removeAttribute("suspended");
504
}
505
}
506
}
507
```
508
509
## Session Statistics
510
511
### Throughput Monitoring
512
513
```java { .api }
514
public class SessionStatistics {
515
516
public void printSessionStats(IoSession session) {
517
// Force throughput calculation
518
session.updateThroughput(System.currentTimeMillis(), true);
519
520
// Basic statistics
521
System.out.println("Session ID: " + session.getId());
522
System.out.println("Creation Time: " + new Date(session.getCreationTime()));
523
System.out.println("Last I/O Time: " + new Date(session.getLastIoTime()));
524
525
// Data transfer statistics
526
System.out.println("Bytes Read: " + session.getReadBytes());
527
System.out.println("Bytes Written: " + session.getWrittenBytes());
528
System.out.println("Messages Read: " + session.getReadMessages());
529
System.out.println("Messages Written: " + session.getWrittenMessages());
530
531
// Throughput statistics
532
System.out.printf("Read Throughput: %.2f bytes/sec%n",
533
session.getReadBytesThroughput());
534
System.out.printf("Write Throughput: %.2f bytes/sec%n",
535
session.getWrittenBytesThroughput());
536
System.out.printf("Read Message Rate: %.2f msgs/sec%n",
537
session.getReadMessagesThroughput());
538
System.out.printf("Write Message Rate: %.2f msgs/sec%n",
539
session.getWrittenMessagesThroughput());
540
541
// Queue statistics
542
System.out.println("Queued Write Messages: " + session.getScheduledWriteMessages());
543
System.out.println("Queued Write Bytes: " + session.getScheduledWriteBytes());
544
}
545
}
546
```
547
548
## Session Initialization
549
550
### Custom Session Initialization
551
552
```java { .api }
553
public class CustomSessionInitializer implements IoSessionInitializer<ConnectFuture> {
554
555
@Override
556
public void initializeSession(IoSession session, ConnectFuture future) {
557
// Configure session during connection
558
session.getConfig().setReadBufferSize(8192);
559
session.getConfig().setIdleTime(IdleStatus.BOTH_IDLE, 60);
560
561
// Set initial attributes
562
session.setAttribute("connectionTime", System.currentTimeMillis());
563
session.setAttribute("protocol", "custom-v1.0");
564
565
// Add session-specific filters
566
session.getFilterChain().addFirst("auth", new AuthenticationFilter());
567
}
568
}
569
570
// Using session initializer with connector
571
IoConnector connector = new NioSocketConnector();
572
CustomSessionInitializer initializer = new CustomSessionInitializer();
573
574
ConnectFuture future = connector.connect(address, initializer);
575
```
576
577
Session management in MINA Core provides comprehensive control over connection lifecycle, configuration, attributes, and statistics, enabling robust and scalable network applications.