org/sonews/daemon/ChannelReader.java
author cli
Thu, 06 Aug 2009 18:41:34 +0200
changeset 6 dcc7e491fbc9
parent 3 2fdc9cc89502
child 15 f2293e8566f5
permissions -rw-r--r--
Removing doc subdir which resides now in sonews-doc repository.
chris@1
     1
/*
chris@1
     2
 *   SONEWS News Server
chris@1
     3
 *   see AUTHORS for the list of contributors
chris@1
     4
 *
chris@1
     5
 *   This program is free software: you can redistribute it and/or modify
chris@1
     6
 *   it under the terms of the GNU General Public License as published by
chris@1
     7
 *   the Free Software Foundation, either version 3 of the License, or
chris@1
     8
 *   (at your option) any later version.
chris@1
     9
 *
chris@1
    10
 *   This program is distributed in the hope that it will be useful,
chris@1
    11
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
chris@1
    12
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
chris@1
    13
 *   GNU General Public License for more details.
chris@1
    14
 *
chris@1
    15
 *   You should have received a copy of the GNU General Public License
chris@1
    16
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
chris@1
    17
 */
chris@1
    18
chris@1
    19
package org.sonews.daemon;
chris@1
    20
chris@1
    21
import java.io.IOException;
chris@1
    22
import java.nio.ByteBuffer;
chris@1
    23
import java.nio.channels.CancelledKeyException;
chris@1
    24
import java.nio.channels.SelectionKey;
chris@1
    25
import java.nio.channels.Selector;
chris@1
    26
import java.nio.channels.SocketChannel;
chris@1
    27
import java.util.Iterator;
chris@1
    28
import java.util.Set;
chris@3
    29
import org.sonews.util.Log;
chris@1
    30
chris@1
    31
/**
chris@1
    32
 * A Thread task listening for OP_READ events from SocketChannels.
chris@1
    33
 * @author Christian Lins
chris@1
    34
 * @since sonews/0.5.0
chris@1
    35
 */
chris@1
    36
class ChannelReader extends AbstractDaemon
chris@1
    37
{
chris@1
    38
chris@1
    39
  private static ChannelReader instance = new ChannelReader();
chris@1
    40
chris@1
    41
  /**
chris@1
    42
   * @return Active ChannelReader instance.
chris@1
    43
   */
chris@1
    44
  public static ChannelReader getInstance()
chris@1
    45
  {
chris@1
    46
    return instance;
chris@1
    47
  }
chris@1
    48
  
chris@1
    49
  private Selector selector = null;
chris@1
    50
  
chris@1
    51
  protected ChannelReader()
chris@1
    52
  {
chris@1
    53
  }
chris@1
    54
  
chris@1
    55
  /**
chris@1
    56
   * Sets the selector which is used by this reader to determine the channel
chris@1
    57
   * to read from.
chris@1
    58
   * @param selector
chris@1
    59
   */
chris@1
    60
  public void setSelector(final Selector selector)
chris@1
    61
  {
chris@1
    62
    this.selector = selector;
chris@1
    63
  }
chris@1
    64
  
chris@1
    65
  /**
chris@1
    66
   * Run loop. Blocks until some data is available in a channel.
chris@1
    67
   */
chris@1
    68
  @Override
chris@1
    69
  public void run()
chris@1
    70
  {
chris@1
    71
    assert selector != null;
chris@1
    72
chris@1
    73
    while(isRunning())
chris@1
    74
    {
chris@1
    75
      try
chris@1
    76
      {
chris@1
    77
        // select() blocks until some SelectableChannels are ready for
chris@1
    78
        // processing. There is no need to lock the selector as we have only
chris@1
    79
        // one thread per selector.
chris@1
    80
        selector.select();
chris@1
    81
chris@1
    82
        // Get list of selection keys with pending events.
chris@1
    83
        // Note: the selected key set is not thread-safe
chris@1
    84
        SocketChannel channel = null;
chris@1
    85
        NNTPConnection conn = null;
chris@1
    86
        final Set<SelectionKey> selKeys = selector.selectedKeys();
chris@1
    87
        SelectionKey selKey = null;
chris@1
    88
chris@1
    89
        synchronized (selKeys)
chris@1
    90
        {
chris@1
    91
          Iterator it = selKeys.iterator();
chris@1
    92
chris@1
    93
          // Process the first pending event
chris@1
    94
          while (it.hasNext())
chris@1
    95
          {
chris@1
    96
            selKey = (SelectionKey) it.next();
chris@1
    97
            channel = (SocketChannel) selKey.channel();
chris@1
    98
            conn = Connections.getInstance().get(channel);
chris@1
    99
chris@1
   100
            // Because we cannot lock the selKey as that would cause a deadlock
chris@1
   101
            // we lock the connection. To preserve the order of the received
chris@1
   102
            // byte blocks a selection key for a connection that has pending
chris@1
   103
            // read events is skipped.
chris@1
   104
            if (conn == null || conn.tryReadLock())
chris@1
   105
            {
chris@1
   106
              // Remove from set to indicate that it's being processed
chris@1
   107
              it.remove();
chris@1
   108
              if (conn != null)
chris@1
   109
              {
chris@1
   110
                break; // End while loop
chris@1
   111
              }
chris@1
   112
            }
chris@1
   113
            else
chris@1
   114
            {
chris@1
   115
              selKey = null;
chris@1
   116
              channel = null;
chris@1
   117
              conn = null;
chris@1
   118
            }
chris@1
   119
          }
chris@1
   120
        }
chris@1
   121
chris@1
   122
        // Do not lock the selKeys while processing because this causes
chris@1
   123
        // a deadlock in sun.nio.ch.SelectorImpl.lockAndDoSelect()
chris@1
   124
        if (selKey != null && channel != null && conn != null)
chris@1
   125
        {
chris@1
   126
          processSelectionKey(conn, channel, selKey);
chris@1
   127
          conn.unlockReadLock();
chris@1
   128
        }
chris@1
   129
chris@1
   130
      }
chris@1
   131
      catch(CancelledKeyException ex)
chris@1
   132
      {
chris@1
   133
        Log.msg("ChannelReader.run(): " + ex, false);
chris@1
   134
        if(Log.isDebug())
chris@1
   135
        {
chris@1
   136
          ex.printStackTrace();
chris@1
   137
        }
chris@1
   138
      }
chris@1
   139
      catch(Exception ex)
chris@1
   140
      {
chris@1
   141
        ex.printStackTrace();
chris@1
   142
      }
chris@1
   143
      
chris@1
   144
      // Eventually wait for a register operation
chris@1
   145
      synchronized (NNTPDaemon.RegisterGate)
chris@1
   146
      {
chris@1
   147
      // Do nothing; FindBugs may warn about an empty synchronized 
chris@1
   148
      // statement, but we cannot use a wait()/notify() mechanism here.
chris@1
   149
      // If we used something like RegisterGate.wait() we block here
chris@1
   150
      // until the NNTPDaemon calls notify(). But the daemon only
chris@1
   151
      // calls notify() if itself is NOT blocked in the listening socket.
chris@1
   152
      }
chris@1
   153
    } // while(isRunning())
chris@1
   154
  }
chris@1
   155
  
chris@1
   156
  private void processSelectionKey(final NNTPConnection connection,
chris@1
   157
    final SocketChannel socketChannel, final SelectionKey selKey)
chris@1
   158
    throws InterruptedException, IOException
chris@1
   159
  {
chris@1
   160
    assert selKey != null;
chris@1
   161
    assert selKey.isReadable();
chris@1
   162
    
chris@1
   163
    // Some bytes are available for reading
chris@1
   164
    if(selKey.isValid())
chris@3
   165
    {   
chris@1
   166
      // Lock the channel
chris@1
   167
      //synchronized(socketChannel)
chris@1
   168
      {
chris@1
   169
        // Read the data into the appropriate buffer
chris@1
   170
        ByteBuffer buf = connection.getInputBuffer();
chris@1
   171
        int read = -1;
chris@1
   172
        try 
chris@1
   173
        {
chris@1
   174
          read = socketChannel.read(buf);
chris@3
   175
        }
chris@3
   176
        catch(IOException ex)
chris@3
   177
        {
chris@3
   178
          // The connection was probably closed by the remote host
chris@3
   179
          // in a non-clean fashion
chris@3
   180
          Log.msg("ChannelReader.processSelectionKey(): " + ex, true);
chris@3
   181
        }
chris@1
   182
        catch(Exception ex) 
chris@1
   183
        {
chris@1
   184
          Log.msg("ChannelReader.processSelectionKey(): " + ex, false);
chris@1
   185
          if(Log.isDebug())
chris@1
   186
          {
chris@1
   187
            ex.printStackTrace();
chris@1
   188
          }
chris@1
   189
        }
chris@1
   190
        
chris@1
   191
        if(read == -1) // End of stream
chris@1
   192
        {
chris@1
   193
          selKey.cancel();
chris@1
   194
        }
chris@1
   195
        else if(read > 0) // If some data was read
chris@1
   196
        {
chris@1
   197
          ConnectionWorker.addChannel(socketChannel);
chris@1
   198
        }
chris@1
   199
      }
chris@1
   200
    }
chris@1
   201
    else
chris@1
   202
    {
chris@1
   203
      // Should not happen
chris@1
   204
      Log.msg(selKey, false);
chris@1
   205
    }
chris@1
   206
  }
chris@1
   207
  
chris@1
   208
}