[英]what is the best way to handle selector keys?
使用選擇器和NIO通道時,我可以有一些(固定的)線程來處理每個可讀鍵嗎? (即每個通道的每個可讀鍵一個線程?)
例如:while(true){
int readyChannels = m_selector.select(1000);
if (0 == readyChannels)
{
continue;
}
Set<SelectionKey> keys = m_selector.selectedKeys();
Iterator<SelectionKey> keyIterator = keys.iterator();
while(keyIterator.hasNext()) {
SelectionKey key = keyIterator.next();
keyIterator.remove();
if (key.isReadable()) {
...
**** WHAT CAN I WRITE HERE TO HANDLE EACH READABLE CHANNEL KEY ONCE ?
**** BECAUSE IF I OPEN NEW THREAD IT WILL NOT FINISH TO HANDLE THE KEY AND I WILL GET
**** TO THIS CODE AGAIN...
...
}
}
}
幾年前,我寫了一個基於NIO的服務器,從處理的數據量和連接的客戶端數量來看,事實證明這是非常高的吞吐量。 我可以基於此分享我的經驗。
請注意,在您的特定情況下,這可能不會100%適用,因此請進行適當的調整。
如果您不執行以下代碼中的數據處理,將會更好
因此將其更改為
if (key.isReadable()) {
...
**** WHAT CAN I WRITE HERE TO HANDLE EACH READABLE CHANNEL KEY ONCE ?
**** BECAUSE IF I OPEN NEW THREAD IT WILL NOT FINISH TO HANDLE THE KEY AND I WILL GET
**** TO THIS CODE AGAIN...
...
}
至
if (key.isReadable()) {
// Sudo logic
// Add the selection key to a thread pool with blocking queue.
// Now your threads in the thread pool will do the heave IO task of reading bytes
// Once the bytes are read you if they need further processing like parsing out what
// Kind of message is it. You can use another thread pool that parses the data
}
如果遵循兩個線程池方法,則有兩個好處。
您可能需要根據自己的情況進行一些線程池調整。
希望對您有所幫助:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.