Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Licensed to the Apache Software Foundation (ASF) under one or more
   * contributor license agreements.  See the NOTICE file distributed with
   * this work for additional information regarding copyright ownership.
   * The ASF licenses this file to You under the Apache License, Version 2.0
   * (the "License"); you may not use this file except in compliance with
   * the License.  You may obtain a copy of the License at
   *
   *      http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package org.apache.catalina.tribes.transport.nio;
 
A worker thread class which can drain channels and echo-back the input. Each instance is constructed with a reference to the owning thread pool object. When started, the thread loops forever waiting to be awakened to service the channel associated with a SelectionKey object. The worker is tasked by calling its serviceChannel() method with a SelectionKey object. The serviceChannel() method stores the key reference in the thread object then calls notify() to wake it up. When the channel has been drained, the worker thread returns itself to its parent pool.
 
 public class NioReplicationTask extends AbstractRxTask {
 
     private static final org.apache.juli.logging.Log log = org.apache.juli.logging.LogFactory.getLogNioReplicationTask.class );
 
     private ByteBuffer buffer = null;
     private SelectionKey key;
     private int rxBufSize;
     private final NioReceiver receiver;
 
     public NioReplicationTask (ListenCallback callbackNioReceiver receiver) {
         super(callback);
         this. = receiver;
     }
 
     // loop forever waiting for work to do
     @Override
     public synchronized void run() {
         if (  == null ) {
             int size = getRxBufSize();
             if (.channel() instanceof DatagramChannel) {
                 size = .;
             }
             if ( (getOptions() & ) == ) {
                  = ByteBuffer.allocateDirect(size);
             } else {
                  = ByteBuffer.allocate(size);
             }
         } else {
             .clear();
         }
         if ( == null) {
             return// just in case
         }
         if ( .isTraceEnabled() )
             .trace("Servicing key:"+);
 
         try {
             ObjectReader reader = (ObjectReader).attachment();
             if ( reader == null ) {
                 if ( .isTraceEnabled() )
                     .trace("No object reader, cancelling:"+);
                 cancelKey();
             } else {
                 if ( .isTraceEnabled() )
                     .trace("Draining channel:"+);
 
                 drainChannel(reader);
             }
         } catch (Exception e) {
            //this is common, since the sockets on the other
            //end expire after a certain time.
            if ( e instanceof CancelledKeyException ) {
                //do nothing
            } else if ( e instanceof IOException ) {
                //dont spew out stack traces for IO exceptions unless debug is enabled.
                if (.isDebugEnabled()) .debug ("IOException in replication worker, unable to drain channel. Probable cause: Keep alive socket closed["+e.getMessage()+"]."e);
                else .warn ("IOException in replication worker, unable to drain channel. Probable cause: Keep alive socket closed["+e.getMessage()+"].");
            } else if ( .isErrorEnabled() ) {
                //this is a real error, log it.
                .error("Exception caught in TcpReplicationThread.drainChannel.",e);
            }
            cancelKey();
        }
         = null;
        // done, ready for more, return to pool
        getTaskPool().returnWorker (this);
    }

    
Called to initiate a unit of work by this worker thread on the provided SelectionKey object. This method is synchronized, as is the run() method, so only one key can be serviced at a given time. Before waking the worker thread, and before returning to the main selection loop, this key's interest set is updated to remove OP_READ. This will cause the selector to ignore read-readiness for this channel while the worker thread is servicing it.
    public synchronized void serviceChannel (SelectionKey key) {
        if ( .isTraceEnabled() ) .trace("About to service key:"+key);
        ObjectReader reader = (ObjectReader)key.attachment();
        if ( reader != null ) reader.setLastAccess(System.currentTimeMillis());
        this. = key;
        key.interestOps (key.interestOps() & (~.));
        key.interestOps (key.interestOps() & (~.));
    }

    
The actual code which drains the channel associated with the given key. This method assumes the key has been modified prior to invocation to turn off selection interest in OP_READ. When this method completes it re-enables OP_READ and calls wakeup() on the selector so the selector will resume watching this channel.
    protected void drainChannel (final SelectionKey keyObjectReader readerthrows Exception {
        reader.setLastAccess(System.currentTimeMillis());
        reader.access();
        ReadableByteChannel channel = (ReadableByteChannelkey.channel();
        int count=-1;
        .clear();         // make buffer empty
        SocketAddress saddr = null;
        if (channel instanceof SocketChannel) {
            // loop while data available, channel is non-blocking
            while ((count = channel.read ()) > 0) {
                .flip();      // make buffer readable
                if ( .hasArray() )
                    reader.append(.array(),0,count,false);
                else
                    reader.append(,count,false);
                .clear();     // make buffer empty
                //do we have at least one package?
                if ( reader.hasPackage() ) break;
            }
        } else if (channel instanceof DatagramChannel) {
            DatagramChannel dchannel = (DatagramChannel)channel;
            saddr = dchannel.receive();
            .flip();      // make buffer readable
            if ( .hasArray() )
                reader.append(.array(),0,.limit()-.position(),false);
            else
                reader.append(,.limit()-.position(),false);
            .clear();     // make buffer empty
            //did we get a package
            count = reader.hasPackage()?1:-1;
        }
        int pkgcnt = reader.count();
        if (count < 0 && pkgcnt == 0 ) {
            //end of stream, and no more packages to process
            remoteEof(key);
            return;
        }
        ChannelMessage[] msgs = pkgcnt == 0? . : reader.execute();
        registerForRead(key,reader);//register to read new data, before we send it off to avoid dead locks
        for ( int i=0; i<msgs.lengthi++ ) {
            
Use send ack here if you want to ack the request to the remote server before completing the request This is considered an asynchronized request
            if (ChannelData.sendAckAsync(msgs[i].getOptions())) sendAck(key,(WritableByteChannel)channel,.,saddr);
            try {
                if ( ..isTraceEnabled() ) {
                    try {
                        ..trace("NioReplicationThread - Received msg:" + new UniqueId(msgs[i].getUniqueId()) + " at " + new java.sql.Timestamp(System.currentTimeMillis()));
                    }catch ( Throwable t ) {}
                }
                //process the message
                getCallback().messageDataReceived(msgs[i]);
                
Use send ack here if you want the request to complete on this server before sending the ack to the remote server This is considered a synchronized request
                if (ChannelData.sendAckSync(msgs[i].getOptions())) sendAck(key,(WritableByteChannel)channel,.,saddr);
            }catch ( RemoteProcessException e ) {
                if ( .isDebugEnabled() ) .error("Processing of cluster message failed.",e);
                if (ChannelData.sendAckSync(msgs[i].getOptions())) sendAck(key,(WritableByteChannel)channel,.,saddr);
            }catch ( Exception e ) {
                .error("Processing of cluster message failed.",e);
                if (ChannelData.sendAckSync(msgs[i].getOptions())) sendAck(key,(WritableByteChannel)channel,.,saddr);
            }
            if ( getUseBufferPool() ) {
                BufferPool.getBufferPool().returnBuffer(msgs[i].getMessage());
                msgs[i].setMessage(null);
            }
        }
        if (count < 0) {
            remoteEof(key);
            return;
        }
    }
    private void remoteEof(SelectionKey key) {
        // close channel on EOF, invalidates the key
        if ( .isDebugEnabled() ) .debug("Channel closed on the remote end, disconnecting");
        cancelKey(key);
    }
    protected void registerForRead(final SelectionKey keyObjectReader reader) {
        if ( .isTraceEnabled() )
            .trace("Adding key for read event:"+key);
        reader.finish();
        //register our OP_READ interest
        Runnable r = new Runnable() {
            @Override
            public void run() {
                try {
                    if (key.isValid()) {
                        // cycle the selector so this key is active again
                        key.selector().wakeup();
                        // resume interest in OP_READ, OP_WRITE
                        int resumeOps = key.interestOps() | .;
                        key.interestOps(resumeOps);
                        if ( .isTraceEnabled() )
                            .trace("Registering key for read:"+key);
                    }
                } catch (CancelledKeyException ckx ) {
                    NioReceiver.cancelledKey(key);
                    if ( .isTraceEnabled() )
                        .trace("CKX Cancelling key:"+key);
                } catch (Exception x) {
                    .error("Error registering key for read:"+key,x);
                }
            }
        };
        .addEvent(r);
    }
    private void cancelKey(final SelectionKey key) {
        if ( .isTraceEnabled() )
            .trace("Adding key for cancel event:"+key);
        ObjectReader reader = (ObjectReader)key.attachment();
        if ( reader != null ) {
            reader.setCancelled(true);
            reader.finish();
        }
        Runnable cx = new Runnable() {
            @Override
            public void run() {
                if ( .isTraceEnabled() )
                    .trace("Cancelling key:"+key);
                NioReceiver.cancelledKey(key);
            }
        };
        .addEvent(cx);
    }


    
send a reply-acknowledgement (6,2,3), sends it doing a busy write, the ACK is so small that it should always go to the buffer

Parameters:
key
channel
    protected void sendAck(SelectionKey keyWritableByteChannel channelbyte[] commandSocketAddress udpaddr) {
        try {
            ByteBuffer buf = ByteBuffer.wrap(command);
            int total = 0;
            if (channel instanceof DatagramChannel) {
                DatagramChannel dchannel = (DatagramChannel)channel;
                //were using a shared channel, document says its thread safe
                //TODO check optimization, one channel per thread?
                while ( total < command.length ) {
                    total += dchannel.send(bufudpaddr);
                }
            } else {
                while ( total < command.length ) {
                    total += channel.write(buf);
                }
            }
            if (.isTraceEnabled()) {
                .trace("ACK sent to " +
                        ( (channel instanceof SocketChannel) ?
                          ((SocketChannel)channel).socket().getInetAddress() :
                          ((DatagramChannel)channel).socket().getInetAddress()));
            }
        } catch ( java.io.IOException x ) {
            .warn("Unable to send ACK back through channel, channel disconnected?: "+x.getMessage());
        }
    }
    public void setRxBufSize(int rxBufSize) {
        this. = rxBufSize;
    }
    public int getRxBufSize() {
        return ;
    }
New to GrepCode? Check out our FAQ X