0

I need to send message to clients from a netty server base on user names of clients. As a result I need to map channels with user name and find the channel each time I want to send message.

I have two approaches in my mind, the question is : Which approach is better, in term of performance in server side. do you have any better idea?

  1. Map channels with user name in a hashmap.

    //Send userName from client side in first request
    //Get userName in server side and put it in a map
    Map<String, Channel> userMap = new ConcurrentHashMap<String,Channel>();    
    //loop over userMap to find specific client 
    
  2. Set Attachment with user name.

    //Set the attachment in client side
    ctx.getChannel().setAttachment(username);
    //Put all channels to a default channel group 
    //Get all channels, search in their attachments to find specific client
    
Nil Null
  • 414
  • 5
  • 14

2 Answers2

1

From your code I suspect that the second option uses linear search to find a specific channel. The first option would simple perform a get. (But the key must be string in this case)

Average linear search time: O(n/2)

Average hashmap access time: O(1)! (see this posting for more information)

That means that the linear search gets worse if you have more channels. The hashmap option is more stable and you can expect almost constant time access.

What you could do is "fuse" both option, so you have the map to access the channels easily and the ChannelGroup for handling the difficult stuff. What you need to do is to remove the channel from the map when its closed.

Community
  • 1
  • 1
morpheus05
  • 4,772
  • 2
  • 32
  • 47
  • But the thing that I consider is handling connection latches and removed channels, that might be a headache and effective on performance. While in the second approach default channel group would take care of it. – Nil Null Jul 30 '14 at 07:43
  • Hmmm, if this operations are far more expensive then the search to access the channel then I would go with the context if it handles this operation well. – morpheus05 Jul 30 '14 at 07:46
  • What do you mean? can you explain more? – Nil Null Jul 30 '14 at 07:56
  • When I think of this, couldn't you use both? ChannelGroup and the map, to find a channel easily? But then you would need some sort of listener, if a channel gets closed you can removed it from the map. – morpheus05 Jul 30 '14 at 08:00
  • Lets say I do it in my ServerHandler which extends SimpleChannelUpstreamHandler . I keep username in handler as well "for the performance" and then remove the channel base on it's user name from the map on channelClosed event. Will it be a good solution ? – Nil Null Jul 30 '14 at 08:17
  • I think you have the best of both worlds with this solution – morpheus05 Jul 30 '14 at 08:24
0

How about creating a "UserInfo" object, which holds the user's name and his associated channel?

Malt
  • 28,965
  • 9
  • 65
  • 105