Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 2085f9d7612251ac64c46c5aa9c1743f228c8f39 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/*
 * Copyright (c) 2012, 2015, 2016 Eike Stepper (Loehne, Germany) and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Eike Stepper - initial API and implementation
 */
package org.eclipse.emf.cdo.internal.common.commit;

import org.eclipse.emf.cdo.common.commit.CDOCommitHistory;

import org.eclipse.net4j.util.event.IListener;
import org.eclipse.net4j.util.lifecycle.ILifecycle;
import org.eclipse.net4j.util.lifecycle.Lifecycle;
import org.eclipse.net4j.util.lifecycle.LifecycleEventAdapter;
import org.eclipse.net4j.util.lifecycle.LifecycleUtil;

import java.util.Map;
import java.util.Map.Entry;
import java.util.WeakHashMap;

/**
 * @author Eike Stepper
 * @since 4.2
 */
public abstract class CDOCommitHistoryProviderImpl<KEY, HISTORY extends CDOCommitHistory> extends Lifecycle implements CDOCommitHistory.Provider<KEY, HISTORY>
{
  private Map<CDOCommitHistory, KEY> histories = new WeakHashMap<CDOCommitHistory, KEY>();

  private IListener historyListener = new LifecycleEventAdapter()
  {
    @Override
    protected void onDeactivated(ILifecycle lifecycle)
    {
      CDOCommitHistory history = (CDOCommitHistory)lifecycle;
      history.removeListener(this);

      synchronized (histories)
      {
        histories.remove(lifecycle);
      }
    }
  };

  public CDOCommitHistoryProviderImpl()
  {
  }

  public CDOCommitHistory getHistory()
  {
    return getHistory(null);
  }

  public HISTORY getHistory(KEY key)
  {
    synchronized (histories)
    {
      for (Entry<CDOCommitHistory, KEY> entry : histories.entrySet())
      {
        KEY currentKey = entry.getValue();
        if (currentKey == key)
        {
          CDOCommitHistory history = entry.getKey();
          return activateHistory(history);
        }
      }

      CDOCommitHistory history = createHistory(key);
      history.addListener(historyListener);
      histories.put(history, key);
      return activateHistory(history);
    }
  }

  protected abstract CDOCommitHistory createHistory(KEY key);

  @SuppressWarnings("unchecked")
  private HISTORY activateHistory(CDOCommitHistory history)
  {
    LifecycleUtil.activate(history);
    return (HISTORY)history;
  }
}

Back to the top