Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: de238a227df1f575795d3105aabaf47c266c2492 (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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
/**
 * Copyright (c) 2004 - 2009 Eike Stepper (Berlin, 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:
 *    Stefan Winkler - initial API and implementation
 */
package org.eclipse.emf.cdo.server.internal.db;

import org.eclipse.emf.cdo.server.internal.db.bundle.OM;

import org.eclipse.net4j.db.DBException;
import org.eclipse.net4j.util.ImplementationError;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashMap;

/**
 * @author Stefan Winkler
 * @since 2.0
 */
public class SmartPreparedStatementCache extends AbstractPreparedStatementCache
{
  private Cache cache;

  private HashMap<PreparedStatement, CachedPreparedStatement> checkedOut = new HashMap<PreparedStatement, CachedPreparedStatement>();

  public SmartPreparedStatementCache(int capacity)
  {
    cache = new Cache(capacity);
  }

  public PreparedStatement getPreparedStatement(String sql, ReuseProbability reuseProbability)
  {
    CachedPreparedStatement cachedStatement = cache.remove(sql);

    if (cachedStatement == null)
    {
      cachedStatement = createCachedPreparedStatement(sql, reuseProbability);
    }

    PreparedStatement result = cachedStatement.getPreparedStatement();
    checkedOut.put(result, cachedStatement);

    return result;
  }

  public void releasePreparedStatement(PreparedStatement ps)
  {
    CachedPreparedStatement cachedStatement = checkedOut.remove(ps);
    cache.put(cachedStatement);
  }

  @Override
  protected void doBeforeDeactivate() throws Exception
  {
    if (!checkedOut.isEmpty())
    {
      OM.LOG.warn("Statement leak detected."); //$NON-NLS-1$
    }
  }

  private CachedPreparedStatement createCachedPreparedStatement(String sql, ReuseProbability reuseProbability)
  {
    PreparedStatement stmt;
    try
    {
      stmt = getConnection().prepareStatement(sql);
      CachedPreparedStatement result = new CachedPreparedStatement(sql, reuseProbability, stmt);
      return result;
    }
    catch (SQLException ex)
    {
      throw new DBException(ex);
    }
  }

  private static final class Cache
  {
    private CacheList lists[];

    private HashMap<String, CachedPreparedStatement> lookup;

    private int capacity;

    public Cache(int capacity)
    {
      this.capacity = capacity;

      lookup = new HashMap<String, CachedPreparedStatement>(capacity);

      lists = new CacheList[ReuseProbability.values().length];
      for (ReuseProbability prob : ReuseProbability.values())
      {
        lists[prob.ordinal()] = new CacheList();
      }
    }

    public void put(CachedPreparedStatement cachedStatement)
    {
      // refresh age
      cachedStatement.touch();

      // put into appripriate list
      lists[cachedStatement.getProbability().ordinal()].add(cachedStatement);

      // put into lookup table
      if (lookup.put(cachedStatement.getSql(), cachedStatement) != null)
      {
        throw new ImplementationError(cachedStatement.getSql() + " already in cache."); //$NON-NLS-1$
      }

      // handle capacity overflow
      if (lookup.size() > capacity)
      {
        evictOne();
      }
    }

    private void evictOne()
    {
      long maxAge = -1;
      int ordinal = -1;

      for (ReuseProbability prob : ReuseProbability.values())
      {
        if (!lists[prob.ordinal()].isEmpty())
        {
          long age = lists[prob.ordinal()].tail().getAge();
          if (maxAge < age)
          {
            maxAge = age;
            ordinal = prob.ordinal();
          }
        }
      }

      remove(lists[ordinal].tail().getSql());
    }

    public CachedPreparedStatement remove(String sql)
    {
      CachedPreparedStatement result = lookup.remove(sql);
      if (result == null)
      {
        return null;
      }
      else
      {
        lists[result.getProbability().ordinal()].remove(result);
        return result;
      }
    }

    private class CacheList
    {
      private CachedPreparedStatement first = null;

      private CachedPreparedStatement last = null;

      public CacheList()
      {
      };

      public void add(CachedPreparedStatement s)
      {
        if (first == null)
        {
          first = s;
          last = s;
          s.previous = null;
          s.next = null;
        }
        else
        {
          first.previous = s;
          s.next = first;
          first = s;
        }
      }

      public void remove(CachedPreparedStatement s)
      {
        if (s == first)
        {
          first = s.next;
        }

        if (s.next != null)
        {
          s.next.previous = s.previous;
        }

        if (s == last)
        {
          last = s.previous;
        }

        if (s.previous != null)
        {
          s.previous.next = s.next;
        }

        s.previous = null;
        s.next = null;
      }

      public CachedPreparedStatement tail()
      {
        return last;
      }

      public boolean isEmpty()
      {
        return first == null;
      }
    }
  };

  private static final class CachedPreparedStatement
  {
    private long timeStamp;

    private String sql;

    private ReuseProbability probability;

    private PreparedStatement statement;

    /**
     * DL field
     */
    private CachedPreparedStatement previous;

    /**
     * DL field
     */
    private CachedPreparedStatement next;

    public CachedPreparedStatement(String sql, ReuseProbability prob, PreparedStatement stmt)
    {
      this.sql = sql;
      probability = prob;
      statement = stmt;
      timeStamp = System.currentTimeMillis();
    }

    public PreparedStatement getPreparedStatement()
    {
      return statement;
    }

    public long getAge()
    {
      long currentTime = System.currentTimeMillis();
      return (currentTime - timeStamp) * probability.ordinal();
    }

    public void touch()
    {
      timeStamp = System.currentTimeMillis();
    }

    public String getSql()
    {
      return sql;
    }

    public ReuseProbability getProbability()
    {
      return probability;
    }
  }
}

Back to the top