"Heartbeat" timeout detection is almost allC/SStructure of the application to handle a problem. The server needs to use it to promptly clean up unexpected client interruptions.This article hopes to change the detection time fromO (Number of all connected clients)DownO (Number of clients that have timed out).
In general, this operation needs to traverse all clients in the connection state to find out which clients have timed out,AlgorithmComplexity:O (N). In a multi-threaded server, you need to lock the list of all clients recorded during the detection. If the algorithm execution time is long, other threads in the system that need to access the list of clients will be blocked.
The following describes the specific measures for changing the space time:
Data Structure
We use a two-way linked list to store the list of connected clients. The addition and receipt of Heartbeat packet processing operations of this list keep the linked list in ascending order of the absolute time of the last heartbeat packet received. Use anotherHashtableTo store the ing between client objects and two-way linked list nodes.
Add new connection
Add a new client to the end of the queue (complexityO (1)), And put the client object and its corresponding double-stranded table Node objectHashtableMedium(Complexity is alsoO (1 )).
Heartbeat Packet Processing
Once the underlying transmission receives the "Heartbeat" packet sent by a clientHashtableExtracts the Node object of a two-way linked list (complexityO (1)) To move the node to the end of the linked list.(Complexity is alsoO (1 )).
Delete Connection
If a client Exits normally or times outHashtableExtracts the Node object of a two-way linked list (complexityO (1)), And thenHashtableDelete the node from the two-way linked list.(Complexity is alsoO (1 )).
"Heartbeat" timeout Detection
the heartbeat status of the client is detected one by one from the header node of the two-way linked list. The detection can be stopped after the first normal client is encountered.