// ResourceReferenceImpl.java
// $Id: ResourceReferenceImpl.java,v 1.5 1997/07/30 14:07:56 ylafon Exp $  
// (c) COPYRIGHT MIT and INRIA, 1997.
// Please first read the full copyright statement in file COPYRIGHT.html

package w3c.tools.resources.impl;

import w3c.tools.resources.*;

public class ResourceReferenceImpl implements ResourceReference {
    /**
     * The lock count associated to the reference.
     */
    protected int lockCount = 0;
    /**
     * The resource we're helding.
     */
    protected Resource pointer = null;
    /**
     * The persistent reference to the resource.
     */
    public PersistentReference pr = null;
    /**
     * Last access time.
     */
    protected long lruDate = 0;
    protected ResourceCache cache = null;

    /**
     * Invalidate that resource reference.
     */

    protected synchronized void invalidate() {
	pointer = null;
	cache.decrMarkCount();
    }

    /**
     * Lock that reference in memory.
     * @return A pointer to the underlying resource, after lock succeed.
     */

    public synchronized Resource lock() {
	if ( pointer == null )
	    pointer = cache.revalidate(this);
	lockCount++;
	if ( lruDate != cache.lruDate )
	    cache.incrMarkCount();
	lruDate = cache.lruDate;
	return pointer;
    }

    /**
     * Unlock that resource reference.
     */

    public synchronized void unlock() {
	if ( lruDate != cache.lruDate )
	    cache.incrMarkCount();
	lruDate = cache.lruDate;
	lockCount--;
    }

    /**
     * Is that resource locked ?
     * @return A boolean, <strong>true</strong> if the resource is locked.
     */

    public boolean isLocked() {
	return lockCount != 0;
    }

    /**
     * Create a new resource reference.
     * @param cache The cache creating the reference.
     * @param pr The persistent resource reference.
     * @param r The resource being refered to.
     */

    protected ResourceReferenceImpl(ResourceCache cache
				    , PersistentReference pr
				    , Resource r) {
	this.cache   = cache;
	this.pr      = pr;
	this.pointer = r;
    }
}
