001/* 002 * Copyright (c) 2006-2011 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * All rights reserved. This program and the accompanying materials 005 * are made available under the terms of the Eclipse Public License v1.0 006 * which accompanies this distribution, and is available at 007 * http://www.eclipse.org/legal/epl-v10.html 008 * 009 * Contributors: 010 * bstefanescu 011 */ 012package org.nuxeo.ecm.core.event.impl; 013 014import java.util.HashMap; 015import java.util.HashSet; 016import java.util.Map; 017import java.util.Set; 018 019/** 020 * A map used to track duplicates. 021 * <p> 022 * This class is not synchronized on read; this means you need to populate the map before using it. 023 * 024 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a> 025 */ 026public class AssocMap { 027 028 protected final Map<String, Set<String>> peers = new HashMap<String, Set<String>>(); 029 030 public synchronized void put(String x, String y) { 031 Set<String> px = peers.get(x); 032 Set<String> py = peers.get(y); 033 if (px == py) { 034 return; // already associated 035 } 036 if (px == null) { 037 py.add(x); 038 peers.put(x, py); 039 } else if (py == null) { 040 px.add(y); 041 peers.put(y, px); 042 } else { // both members are already in relation with other members 043 Set<String> set = new HashSet<String>(); 044 set.addAll(px); 045 set.addAll(py); 046 for (String key : set.toArray(new String[set.size()])) { 047 peers.put(key, set); 048 } 049 } 050 } 051 052 public boolean isPeerOf(String x, String y) { 053 Set<String> set = peers.get(x); 054 return set != null && set.contains(y); 055 } 056 057}