mat wrote:
> Hi folks,
>
> If the code is correct? do I need synchronized (sessions)?
>
> I have a hashtable to maintain the IoSession.
>
> public void onBroadcasting(MyMessage message)
> {
>  Enumeration e = sessions.elements();
>
>  while(e.hasMoreElements())
>  {
>   IoSession session = (IoSession)e.nextElement();
>      session.write(message);
>  }
> }
>
>
> However, in mina chat example. Is it neccessary to synchronized(
> sessions )?
>
>
>    public void broadcast( String message )
>    {
>        synchronized( sessions )
>        {
>            Iterator iter = sessions.iterator();
>            while( iter.hasNext() )
>            {
>                IoSession s = ( IoSession ) iter.next();
>                if( s.isConnected() )
>                {
>                    s.write( "BROADCAST OK " + message );
>                }
>            }
>        }
>    }
>

Depends on what Collection you are using to store the sessions. In the
chat example we need to synchronize because if a new client connects
while we are iterating over the elements we would get a
ConcurrentModificationException without the synchronization.

Hashtable.iterator() and listIterator() are fail-fast which means that
they throw ConcurrentModificationException if the Hashtable is changed
while iterating (not changed using the Iterator's methods). The
Enumeration returned by Hashtable.elements() is not fail-fast. I think
that means that things can go horribly wrong at any time (fast or slow)
if the Hashtable is modified. :-)

-- 
Niklas Therning
www.spamdrain.net

Reply via email to