001/* 002 * This library is part of OpenCms - 003 * the Open Source Content Management System 004 * 005 * Copyright (C) Alkacon Software (http://www.alkacon.com) 006 * 007 * This library is free software; you can redistribute it and/or 008 * modify it under the terms of the GNU Lesser General Public 009 * License as published by the Free Software Foundation; either 010 * version 2.1 of the License, or (at your option) any later version. 011 * 012 * This library is distributed in the hope that it will be useful, 013 * but WITHOUT ANY WARRANTY; without even the implied warranty of 014 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 015 * Lesser General Public License for more details. 016 * 017 * For further information about Alkacon Software, please see the 018 * company website: http://www.alkacon.com 019 * 020 * For further information about OpenCms, please see the 021 * project website: http://www.opencms.org 022 * 023 * You should have received a copy of the GNU Lesser General Public 024 * License along with this library; if not, write to the Free Software 025 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 026 */ 027 028package org.opencms.gwt.client.util; 029 030import java.util.HashSet; 031import java.util.Set; 032 033/** 034 * Helper class used to perform an action when multiple asynchronous tasks have finished.<p> 035 * 036 * To use this, first, for every action, add a token which uniquely identifies the action. Remove the corresponding 037 * token when the action is finished. When all tokens are removed, the final action will be executed.<p> 038 */ 039public class CmsAsyncJoinHandler { 040 041 /** The action to perform when all tokens have been removed. */ 042 private Runnable m_joinAction; 043 044 /** The set of tokens. */ 045 protected Set<Object> m_tokens = new HashSet<Object>(); 046 047 /** 048 * Creates a new instance.<p> 049 * 050 * @param joinAction the final action to execute 051 */ 052 public CmsAsyncJoinHandler(Runnable joinAction) { 053 054 m_joinAction = joinAction; 055 } 056 057 /** 058 * Adds tokens.<p> 059 * 060 * @param tokens the tokens to add 061 */ 062 public void addTokens(Object... tokens) { 063 064 for (Object token : tokens) { 065 m_tokens.add(token); 066 } 067 } 068 069 /** 070 * Removes a token.<p> 071 * 072 * When all tokens have been removed, the final action is executed.<p> 073 * 074 * @param token the token to remove 075 */ 076 public void removeToken(Object token) { 077 078 m_tokens.remove(token); 079 if (m_tokens.isEmpty()) { 080 if (m_joinAction != null) { 081 m_joinAction.run(); 082 } 083 } 084 } 085 086}