⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 cacher.java

📁 实现LRU算法的Cache源代码
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
	// }
	//
	// synType = syn;
	// /*
	// if(synType==CacherSyner.SYN_SAME)
	// {
	// beforeInit(boolean clearexisted)
	// }*/
	//
	// cacherSyn.myTypeChange(strCacherName, syn);
	// }
	//
	// void setSynTypeNoSyn(short syn)
	// {
	// if (syn == CacherSyner.SYN_UNIQUE)
	// {
	// throw new RuntimeException("Not Support Unique Syner now!");
	// }
	// synType = syn;
	// }
	//
	// public short getSynType()
	// {
	// return synType;
	// }

	public void setCacheLength(int len)
	{
		// if (synType == CacherSyner.SYN_SAME_MEM)
		// { //判断是否处于冰冻状态,如果是就阻塞
		// if (bFreezen)
		// {
		// try
		// {
		// wait();
		// setCacheLength(len);
		// }
		// catch (Exception e)
		// {}
		// }
		// }

		setCacheLengthNoSyn(len);

		// cacherSyn.mySetCacheLength(strCacherName, len);
	}

	void setCacheLengthNoSyn(int len)
	{
		cacherBuffer.setMaxBufferLen(len);
	}

	public int getCacheLength()
	{
		return cacherBuffer.getMaxBufferLen();
	}

	public int getContentLength()
	{
		return cacherBuffer.getBufferLen();
	}

	// void addToBufferDuringInit(Object o)
	// {
	// if (synType != CacherSyner.SYN_SAME)
	// {
	// throw new RuntimeException("Error Cache[" + strCacherName +
	// "],Only SYN_SAME cannot do During Init buffering!");
	// }
	// if (initState != DURING_INIT)
	// {
	// throw new RuntimeException("Error Cache[" + strCacherName +
	// "],Only During Init can buffering!");
	// }
	// duringInitBuf.addElement(o);
	// }

	private boolean bFreezen = false;

	void setFreezen(boolean bfreezen)
	{
		bFreezen = bfreezen;
		if (!bFreezen)
		{
			notify();
		}
	}

	boolean isFreezen()
	{
		return bFreezen;
	}

	/**
	 * 对某个对象进行保存 1,如果没有做同步,直接保存并返回 2,如果有脏同步,则发送一个myChange事件
	 * 3,如果有唯一同步,则先判断自己是否是主机(主机以IP地址小的为主), 如果不是:将该对象发送到主机 如果是:直接保存
	 * 
	 * @param id
	 *            该对象使用的id
	 * @param ob
	 *            对象指针
	 * @param lifttime
	 *            该对象在cache中保留的时间
	 */
	public void cache(Object key, Object ob, long livetime, boolean refresh)
	{ // System.out.println
		// ("cache---------["+this.strCacherName+"]["+key+"]["+ob+"]>>>>>") ;
	// if (synType == CacherSyner.SYN_SAME)
	// {
	// switch (initState)
	// {
	// case UNKNOW_INIT:
	// throw new RuntimeException(
	// "Not set beforeInit for this SYN_SAME cache[" +
	// strCacherName + "]!");
	// case BEFORE_INIT:
	// throw new RuntimeException(
	// "Not set beginInit for this SYN_SAME cache[" +
	// strCacherName + "]!");
	// }
	// }
	// else if (synType == CacherSyner.SYN_SAME_MEM)
	// { //判断是否处于冰冻状态,如果是就阻塞
	// if (bFreezen)
	// {
	// try
	// {
	// wait();
	// cache(key, ob, livetime, refresh);
	// }
	// catch (Exception e)
	// {}
	// }
	// }

		Shell tmpsh = null;
		boolean bnew = false;
		synchronized (this)
		{
			tmpsh = cacherBuffer.accessShell(key);

			if (tmpsh == null)
			{
				tmpsh = new Shell(key, ob, livetime, refresh);
				cacherBuffer.addShell(tmpsh);
				bnew = true;
			}
			else
			{
				tmpsh.setContent(ob);
				tmpsh.setRefresh(refresh);
				tmpsh.setLiveTime(livetime);
				bnew = false;
			}
		}

		pulseClean();
		
		// switch (synType)
		// {
		// case CacherSyner.SYN_NO:
		// break;
		// case CacherSyner.SYN_DIRTY:
		// if (!bnew)
		// {
		// cacherSyn.myRemove(strCacherName, key);
		// }
		// break;
		// case CacherSyner.SYN_CHANGE:
		// cacherSyn.myAddOrChange(strCacherName, tmpsh);
		// break;
		// case CacherSyner.SYN_SAME:
		// if (initState == AFTER_INIT)
		// {
		// cacherSyn.myAddOrChange(strCacherName, tmpsh);
		// }
		// break;
		// case CacherSyner.SYN_UNIQUE:
		//
		// //cacherSyn.myAddOrChange(strCacherName,tmpsh) ;
		// //throw new RuntimeException("") ;
		// break;
		// }
	}

	/*
	 * public void update (Object key,Object ob,long livetime,boolean refresh) {
	 * Shell tmpsh = null ; synchronized (this) { tmpsh =
	 * cacherBuffer.accessShell (key) ; if (tmpsh==null) { tmpsh = new Shell
	 * (key,ob,livetime,refresh) ; cacherBuffer.addShell (tmpsh) ; } else {
	 * tmpsh.setContent (ob) ; tmpsh.setRefresh (refresh) ; tmpsh.setLiveTime
	 * (livetime) ; } } switch (synType) { case CacherSyner.SYN_NO: break ; case
	 * CacherSyner.SYN_DIRTY: cacherSyn.myRemove(strCacherName,key) ; break ;
	 * case CacherSyner.SYN_SAME: cacherSyn.myAddOrChange(strCacherName,tmpsh) ;
	 * break ; case CacherSyner.SYN_UNIQUE:
	 * //cacherSyn.myAddOrChange(strCacherName,tmpsh) ; //throw new
	 * RuntimeException("") ; break ; } }
	 */
	// public void cacheNoSyn (Object key,
	public void cache(Object key, Object ob, long livetime)
	{
		cache(key, ob, livetime, true);
	}

	/**
	 * 对某个对象进行保存,在cache中保留的时间为缺省值
	 * 
	 * @param id
	 *            该对象使用的id
	 * @param ob
	 *            对象指针
	 */
	public void cache(Object key, Object ob)
	{
		cache(key, ob, -1);
	}

	/**
	 * 获得一个缓冲内容的存活时间。
	 * 
	 * @return long 0表示不存在该内容,-1表示永久,>0表示具体时间
	 */
	public long getLiveTime(Object key)
	{
		Shell tmpsh = cacherBuffer.getShell(key);
		if (tmpsh == null)
		{
			return 0;
		}
		if (tmpsh.isTimeOut())
		{
			cacherBuffer.removeShell(tmpsh);
			return 0;
		}
		return tmpsh.getLiveTime();
	}

	/**
	 * 删除一个缓冲内容
	 */
	public Object remove(Object key)
	{
		// if (synType == CacherSyner.SYN_SAME_MEM)
		// { //判断是否处于冰冻状态,如果是就阻塞
		// if (bFreezen)
		// {
		// try
		// {
		// wait();
		// remove(key);
		// }
		// catch (Exception e)
		// {}
		// }
		// }

		Shell tmpsh = cacherBuffer.removeShell(key);
		if (tmpsh == null)
		{
			return null;
		}

		// if (synType == CacherSyner.SYN_NO)
		// {
		// return tmpsh.getContent();
		// }
		//
		// if ( (synType == CacherSyner.SYN_SAME) && (initState != AFTER_INIT))
		// {
		// return tmpsh.getContent();
		// }
		//
		// cacherSyn.myRemove(strCacherName, key);

		return tmpsh.getContent();
	}

	void removeNoSyn(Object key)
	{
		cacherBuffer.removeShell(key);
	}

	/**
	 * 获取缓冲中的所有内容的key,但不能保证所有的key,在以后的 使用过程中都可以获得内容。
	 */
	public Object[] getAllKeys()
	{
		Shell[] tmpsh = cacherBuffer.getAllShell();
		Object[] keys = new Object[tmpsh.length];
		for (int i = 0; i < tmpsh.length; i++)
		{
			keys[i] = tmpsh[i].getKey();
		}
		return keys;
	}

	/**
	 * 获取缓冲中的所有内容的key,但不能保证所有的key,在以后的 使用过程中都可以获得内容。
	 */
	public Enumeration getAllKeysEnum()
	{
		return cacherBuffer.getAllKeys();
	}

	/**
	 * 获取缓冲中的所有内容
	 */
	public Object[] getAllContents()
	{
		Shell[] tmpsh = cacherBuffer.getAllShell();
		Object[] conts = new Object[tmpsh.length];
		for (int i = 0; i < tmpsh.length; i++)
		{
			conts[i] = tmpsh[i].peekContent();
		}
		return conts;
	}

	/**
	 * 清空缓冲中的所有内容
	 */
	public void clear()
	{
		// if (synType == CacherSyner.SYN_SAME_MEM)
		// { //判断是否处于冰冻状态,如果是就阻塞
		// if (bFreezen)
		// {
		// try
		// {
		// wait();
		// clear();
		// }
		// catch (Exception e)
		// {}
		// }
		// }

		cacherBuffer.emptyBuffer();

		// if (synType == CacherSyner.SYN_NO)
		// {
		// return;
		// }
		//
		// if ( (synType == CacherSyner.SYN_SAME) && (initState != AFTER_INIT))
		// {
		// return;
		// }
		//
		// cacherSyn.myClear(strCacherName);
	}

	public boolean isEmpty()
	{
		return cacherBuffer.isEmpty();
	}

	public int size()
	{
		return cacherBuffer.size();
	}

	void clearNoSyn()
	{
		cacherBuffer.emptyBuffer();
	}

	/**
	 * 
	 */
	synchronized public Object get(Object key)
	{
		pulseClean();
		
		if (_DEBUG)
		{
			return null;
		}
		/*
		 * if (synType==CacherSyner.SYN_UNIQUE) {//对于唯一同步,使用最小ip作为主机,如果不是主机
		 * //则返回null if (!CacherSyner.getInstance().isSmallestIP()) return null ; }
		 */
		Shell tmpsh = cacherBuffer.accessShell(key);
		if (tmpsh == null)
		{
			return null;
		}
		if (tmpsh.isTimeOut())
		{
			cacherBuffer.removeShell(tmpsh);
			return null;
		}
		
		return tmpsh.getContent();
	}

	public Object peek(Object key)
	{
		Shell tmpsh = cacherBuffer.getShell(key);
		if (tmpsh == null)
		{
			return null;
		}
		if (tmpsh.isTimeOut())
		{
			cacherBuffer.removeShell(tmpsh);
			return null;
		}
		return tmpsh.getContent();
	}

	synchronized public void detectExpired()
	{
		Shell[] shs = cacherBuffer.getAllShell();
		for (int i = 0; i < shs.length; i++)
		{
			if (shs[i].isTimeOut())
			{
				cacherBuffer.removeShell(shs[i]);
			}
		}
	}

	public void setMaxBufferLength(int len)
	{
		setCacheLength(len);
	}

	public Shell[] getAllShell()
	{
		return cacherBuffer.getAllShell();
	}

	public CacherBuffer getCacherBuffer()
	{
		return cacherBuffer;
	}

	public void list()
	{
		/*
		 * System.out.println ("-----In cache has----------------") ; Shell[]
		 * shs = cacherBuffer.getAllShell () ; for (int i = 0 ; i < shs.length ;
		 * i ++) System.out.println (shs[i].toString()) ; System.out.println
		 * ("---------------------------------") ;
		 */
		cacherBuffer.list();
	}

	// ///////////////////////////////////////////
	public static void main(String args[])
	{
		try
		{
			Cacher cah = Cacher.getCacher();

			String inputLine;
			BufferedReader in = new BufferedReader(new InputStreamReader(
					System.in));
			while ((inputLine = in.readLine()) != null)
			{
				StringTokenizer st = new StringTokenizer(inputLine);
				int c = st.countTokens();
				String cmd[] = new String[c];
				for (int i = 0; i < c; i++)
				{
					cmd[i] = st.nextToken();
				}
				if (cmd.length == 0)
				{
					continue;
				}

				if (cmd[0].equals("cache"))
				{ //
					int l = cmd.length;
					if (l == 5)
					{
						cah.cache(cmd[1], cmd[2], Integer.parseInt(cmd[3]),
								Boolean.valueOf(cmd[4]).booleanValue());
					}
					else if (l == 4)
					{
						cah.cache(cmd[1], cmd[2], Integer.parseInt(cmd[3]));
					}
					else if (l == 3)
					{
						cah.cache(cmd[1], cmd[2]);
					}
				}
				else if (cmd[0].equals("ls"))
				{
					cah.list();
				}
				else if (cmd[0].equals("get"))
				{
					Object ob = cah.get(cmd[1]);
					System.out.println("" + ob);
				}
				else if (cmd[0].equals("setMaxBufferLength"))
				{
					cah.setMaxBufferLength(Integer.parseInt(cmd[1]));
				}
				else if (cmd[0].equals("remove"))
				{
					System.out.println("" + cah.remove(cmd[1]));
				}
				else if (cmd[0].equals("clear"))
				{
					cah.clear();
				}
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -