/**
 *
 * Copyright 2004 Hiram Chirino
 *
 *  Licensed 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.activeio.filter;

import java.io.IOException;
import java.io.InterruptedIOException;

import org.activeio.AsynchChannel;
import org.activeio.FilterAsynchChannel;
import org.activeio.Packet;

import EDU.oswego.cs.dl.util.concurrent.Mutex;
import EDU.oswego.cs.dl.util.concurrent.Sync;

/**
 * Used to synchronize concurrent access to an ASynchChannel.  
 * 
 * Uses a {@see EDU.oswego.cs.dl.util.concurrent.Sync} object
 * for write operations.  All other operations such as {@see #stop(long)}
 * and {@see #stop} just do a normal java synchronization against the SynchornizedSynchChannel
 * object instance.  It is assumed that the Async message delivery is not 
 * concurrent and therefore does not require synchronization.
 * 
 */
public class SynchornizedAsynchChannel extends FilterAsynchChannel {

    private final Sync writeLock;

    public SynchornizedAsynchChannel(AsynchChannel next) {
        this(next, new Mutex());
    }
    
    public SynchornizedAsynchChannel(AsynchChannel next, Sync writeLock) {
        super(next);
        this.writeLock = writeLock;
    }    
    
    public void write(Packet packet) throws IOException {
        try {                        
            writeLock.acquire();
        } catch (InterruptedException e) {
            throw new InterruptedIOException(e.getMessage());
        }
        try {
            getNext().write(packet);            
        } finally {
            writeLock.release();
        }
    }
    
    public void flush() throws IOException {
        try {                        
            writeLock.acquire();
        } catch (InterruptedException e) {
            throw new InterruptedIOException(e.getMessage());
        }
        try {
            getNext().flush();            
        } finally {
            writeLock.release();
        }
    }

    synchronized public void dispose() {
        super.dispose();
    }

    synchronized public Object narrow(Class target) {
        return super.narrow(target);
    }

    synchronized public void start() throws IOException {
        super.start();
    }

    synchronized public void stop(long timeout) throws IOException {
        super.stop(timeout);
    }
    
    public Sync getWriteLock() {
        return writeLock;
    }
}
