/*
 * 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.myfaces.orchestra.lib;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


/**
 * A reentrant mutual exclusion with the same basic
 * behavior and semantics as the implicit monitor lock accessed using
 * {@code synchronized} methods and statements.
 * <p>
 * Serialization of this class behaves in the same way as built-in
 * locks: a deserialized lock is in the unlocked state, regardless of
 * its state when serialized.
 * <p>
 * This class exists just for the purposes of Java 1.4 compatibility;
 * it is equivalent to the Java 1.5 ReentrantLock class. It probably
 * doesn't perform as well as the "real" lock class, but Orchestra
 * doesn't use it in any critical paths.
 * 
 * @since 1.1
 */
public class _ReentrantLock implements java.io.Serializable
{
    private static final long serialVersionUID = 7373984872572414699L;
    private static final long WAIT_WARN_MILLIS = 30L * 1000L; // 30 seconds

    private final Log log = LogFactory.getLog(_ReentrantLock.class);
    private transient Thread lockedBy;
    private int lockCount;
    
    public void lockInterruptibly() throws InterruptedException
    {
        Thread caller = Thread.currentThread();
        for(;;)
        {
            synchronized(this)
            {
                if (lockedBy == null)
                {
                    lockedBy = caller;
                    lockCount = 1;
                    return;
                } 
    
                if (lockedBy == caller)
                {
                    ++lockCount;
                    return;
                }

                long waitedFor;
                try
                {
                    if (log.isDebugEnabled())
                    {
                        log.debug("Waiting for lock " + this.toString()
                                + " which is owned by thread "
                                + lockedBy.getName());
                    }
                    long beganAt = System.currentTimeMillis();
                    this.wait(WAIT_WARN_MILLIS);
                    waitedFor = System.currentTimeMillis() - beganAt;
                }
                catch(InterruptedException e)
                {
                    throw e;
                }
                
                if (waitedFor >= WAIT_WARN_MILLIS)
                {
                    // Hopefully this will not get invoked very often!
                    if (log.isWarnEnabled())
                    {
                        String lockedByName;
                        if (lockedBy != null)
                        {
                            lockedByName = lockedBy.getName();
                        }
                        else
                        {
                            // Unlikely but possible due to race conditions
                            lockedByName = "(none)";
                        }
                        log.warn("Waited for longer than " + WAIT_WARN_MILLIS 
                            + " milliseconds for access to lock " + this.toString()
                            + " which is locked by thread " + lockedByName);
                    }
                }
            }
        }
    }
    
    public void unlock()
    {
        Thread caller = Thread.currentThread();
        synchronized(this)
        {
            if (lockedBy != caller)
            {
                throw new IllegalStateException("Unlock on lock not owned by caller");
            }
            
            --lockCount;
            if (lockCount == 0)
            {
                lockedBy = null;
                this.notifyAll();
            }
        }
    }
    
    public boolean isHeldByCurrentThread()
    {
        Thread caller = Thread.currentThread();
        synchronized(this)
        {
            return lockedBy == caller;
        }
    }
}
