互斥访问,限制最大数访问

/**
 * @author jgao1 
 * 用法:PortfolioManager portfolioManager = PortfolioManager.getInstance();
 *       portfolioManager.calculateMvoByXMLString(configXml,inputXml,timOut);
 */
public class PortfolioManager {

	private static PortfolioManager instance; // 唯一实例
	private static int MaxClients = 30;// 最大连接数
	private static int clients; // 连接的客户端

	/**
	 * 单例模式建构私有函数以防止其它对象创建本类实例
	 */
	private PortfolioManager() {

	}

	/**
	 * 采用单例模式,返回唯一实例.如果是第一次调用此方法,则创建实例
	 * 
	 * @return 唯一实例
	 */
	public static synchronized PortfolioManager getInstance() {
		if (instance == null) {
			instance = new PortfolioManager();
		}
		return instance;
	}

	/**
	 * 计算MVO
	 * 
	 * @param configXml
	 * @param inputXml
	 * @param timOut:毫秒
	 * @return
	 */
	public synchronized String calculateMvoByXMLString(String configXml,
			String inputXml, long timOut) {
		String outPutXml = null;
		clients++;
		if (clients <= MaxClients) {
			try {
				outPutXml = PortfolioUtils.calculateMvoByXMLString(configXml,
						inputXml);
				freeClient();
			} catch (Exception e) {
				freeClient();
			}
		} else {
			long startTime = System.currentTimeMillis();
			while (!(clients <= MaxClients)) {
				try {
					wait(timOut);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				if ((System.currentTimeMillis() - startTime) >= timOut) {
					// 记录log日志
					return null;// 超时返回为空
				}
			}
			try {
				outPutXml = PortfolioUtils.calculateMvoByXMLString(configXml,
						inputXml);
				freeClient();
			} catch (Exception e) {
				freeClient();
			}
		}
		return outPutXml;
	}

	/**
	 * 同步減少客户端的连接
	 */
	public synchronized void freeClient() {
		clients--;
		notifyAll();// 唤醒其他等待的线程
	}
}

 

你可能感兴趣的:(互斥)