File: MemoryStress.java

package info (click to toggle)
libdb-je-java 3.3.62-3
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 12,832 kB
  • ctags: 18,708
  • sloc: java: 149,906; xml: 1,980; makefile: 14; sh: 12
file content (430 lines) | stat: -rw-r--r-- 15,976 bytes parent folder | download | duplicates (4)
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
import java.io.File;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Iterator;
import java.util.Random;

import com.sleepycat.bind.tuple.IntegerBinding;
import com.sleepycat.je.BtreeStats;
import com.sleepycat.je.Cursor;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseConfig;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.DbInternal;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;
import com.sleepycat.je.EnvironmentStats;
import com.sleepycat.je.OperationStatus;
import com.sleepycat.je.StatsConfig;
import com.sleepycat.je.Transaction;
import com.sleepycat.je.dbi.EnvironmentImpl;
import com.sleepycat.je.dbi.INList;
import com.sleepycat.je.dbi.MemoryBudget;
import com.sleepycat.je.incomp.INCompressor;
import com.sleepycat.je.tree.BIN;
import com.sleepycat.je.tree.IN;

/**
 * The original version of this test was written by Brian O'Neill of Amazon,
 * for SR 11163. It used to get OutOfMemoryError at 720,000 records on Linda's
 * laptop, on JE 1.5.3.
 */
public class MemoryStress {
    private Environment env;
    private Database db;
    private StatsConfig statsConfig;
    private EnvironmentImpl envImpl;

    private DecimalFormat decimalFormat;
    private NumberFormat numberFormat;

    private int reportingInterval = 10000;
    private int nextSerialKey = 0;

    private String environmentHome;
    private int numThreads;
    private boolean insertDups;
    private boolean serialKeys;
    private boolean doDelete;
    private boolean deleteExisting;
    private int totalOps = Integer.MAX_VALUE;

    /* accumulated stats */
    private int totalEvictPasses;
    private int totalSelected;
    private int totalScanned;
    private int totalExEvicted;
    private int totalStripped;
    private int totalCkpts;
    private int totalCleaned;
    private int totalNotResident;
    private int totalCacheMiss;

    public static void main(String[] args) {
        try {
            MemoryStress ms = new MemoryStress();
            for (int i = 0; i < args.length; i += 1) {
                String arg = args[i];
                String arg2 = (i < args.length - 1) ? args[i + 1] : null;
                if (arg.equals("-h")) {
                    if (arg2 == null) {
                        throw new IllegalArgumentException(arg);
                    }
                    ms.environmentHome = arg2;
                    i += 1;
                } else if (arg.equals("-nThreads")) {
                    if (arg2 == null) {
                        throw new IllegalArgumentException(arg);
                    }
                    try {
                        ms.numThreads = Integer.parseInt(arg2);
                    } catch (NumberFormatException e) {
                        throw new IllegalArgumentException(arg2);
                    }
                    i += 1;
                } else if (arg.equals("-nOps")) {
                    if (arg2 == null) {
                        throw new IllegalArgumentException(arg);
                    }
                    try {
                        ms.totalOps = Integer.parseInt(arg2);
                    } catch (NumberFormatException e) {
                        throw new IllegalArgumentException(arg2);
                    }
                    i += 1;
                } else if (arg.equals("-dups")) {
                    ms.insertDups = true;
                } else if (arg.equals("-serial")) {
                    ms.serialKeys = true;
                } else if (arg.equals("-delete")) {
                    ms.doDelete = true;
                } else if (arg.equals("-deleteExisting")) {
                    ms.deleteExisting = true;
                } else {
                    throw new IllegalArgumentException(arg);
                }
            }
            if (ms.environmentHome == null) {
                throw new IllegalArgumentException("-h not specified");
            }
            ms.run();
            System.exit(0);
        } catch (IllegalArgumentException e) {
            System.out.println(
                "Usage: MemoryStress -h <envHome> [-nThreads <nThreads>" +
                "-nOps <nOps> -dups -serial -delete -deleteExisting]");
            e.printStackTrace();
            System.exit(2);
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    MemoryStress() {
        decimalFormat = new DecimalFormat();
        decimalFormat.setMaximumFractionDigits(2);
        decimalFormat.setMinimumFractionDigits(2);

        numberFormat = NumberFormat.getInstance();

        statsConfig = new StatsConfig();
        statsConfig.setFast(true);
        statsConfig.setClear(true);
    }

    void run()
        throws DatabaseException, InterruptedException  {

        EnvironmentConfig envConfig = new EnvironmentConfig();
        envConfig.setTransactional(true);
        envConfig.setReadOnly(false);
        envConfig.setAllowCreate(true);
        envConfig.setTxnNoSync(true);

        env = new Environment(new File(environmentHome), envConfig);

        EnvironmentConfig seeConfig = env.getConfig();
        System.out.println("maxMem = " +
                           numberFormat.format(seeConfig.getCacheSize()));
        System.out.println(seeConfig);
        envImpl = DbInternal.envGetEnvironmentImpl(env);

        DatabaseConfig dbConfig = new DatabaseConfig();
        dbConfig.setSortedDuplicates(insertDups);
        dbConfig.setTransactional(true);
        dbConfig.setReadOnly(false);
        dbConfig.setAllowCreate(true);

        db = env.openDatabase(null, "test", dbConfig);

        Worker[] workers = new Worker[numThreads];
        for (int i = 0; i < numThreads; i++) {
            Worker w = new Worker(i, db, totalOps);
            w.start();
            workers[i] = w;
        }

        for (int i = 0; i < numThreads; i++) {
            workers[i].join();
        }

        db.close();

        long startTime = System.currentTimeMillis();
        env.close();
        String timeStr = numberFormat.format
            ((System.currentTimeMillis() - startTime)/1e3);
        System.out.println("Environment.close took " + timeStr + " seconds");
    }

    private class Worker extends Thread {

        public int id;
        Database db;
        private int totalOps;

        Worker(int id, Database db, int totalOps) {
            this.id = id;
            this.db = db;
            this.totalOps = totalOps;
        }

        public void run() {
            int count = 0;
            Random rnd = new Random(4361 + id);
            byte[] key = new byte[10];
            byte[] value = new byte[100];

            long start = System.currentTimeMillis();

            DatabaseEntry keyEntry = new DatabaseEntry();
            DatabaseEntry valueEntry = new DatabaseEntry();

            try {
                int intervalCount = 0;
                long intervalStart = start;
                while (count < totalOps) {
                    if (deleteExisting) {
                        Transaction txn = env.beginTransaction(null, null);
                        Cursor cursor = db.openCursor(txn, null);
                        OperationStatus status =
                            cursor.getFirst(keyEntry, valueEntry, null);
                        if (status == OperationStatus.SUCCESS) {
                            cursor.delete();
                        }
                        cursor.close();
                        txn.commit();
                        if (status == OperationStatus.SUCCESS) {
                            count += 1;
                        } else {
                            System.out.println("No more records");
                            break;
                        }
                    } else {
                        if (serialKeys) {
                            int keyValue = getNextSerialKey();
                            IntegerBinding.intToEntry(keyValue, keyEntry);
                            System.arraycopy(keyEntry.getData(), 0, key, 0, 4);
                            keyEntry.setData(key);
                        } else {
                            rnd.nextBytes(key);
                            keyEntry.setData(key);
                        }
                        rnd.nextBytes(value);
                        valueEntry.setData(value);

                        db.put(null, keyEntry, valueEntry);
                        count++;
                        intervalCount++;

                        if (insertDups) {
                            for (int i = 0; i < 3; i += 1) {
                                rnd.nextBytes(value);
                                valueEntry.setData(value);
                                db.put(null, keyEntry, valueEntry);
                                count += 1;
                            }
                        }

                        if (doDelete) {
                            db.delete(null, keyEntry);
                        }
                    }

                    if (count % reportingInterval == 0) {
                        reportStats(id, intervalCount, count,
                                    intervalStart, start, db);
                        intervalCount = 0;
                        intervalStart = System.currentTimeMillis();
                    }
                }
                reportStats(id, intervalCount, count,
                            intervalStart, start, db);
            } catch (DatabaseException e) {
                e.printStackTrace();
            }
        }
    }

    private synchronized int getNextSerialKey() {
        return nextSerialKey++;
    }

    private void reportStats(int threadId,
                             int intervalCount,
                             int count,
                             long intervalStart,
                             long start,
                             Database db)
        throws DatabaseException {

        long end = System.currentTimeMillis();

        double seconds = (end - start)/1e3;
        double intervalSeconds = (end - intervalStart)/1e3;
        double rate = (double)(intervalCount/intervalSeconds);
        double totalRate = (double)(count/seconds);
        MemoryBudget mb = envImpl.getMemoryBudget();
        INList inList = envImpl.getInMemoryINs();
        INCompressor compressor = envImpl.getINCompressor();
        EnvironmentStats stats = env.getStats(statsConfig);
        System.out.println("id=" + threadId +
                           " " +  numberFormat.format(count) +
                           " rate=" +
                           decimalFormat.format(rate) +
                           " totalRate=" +
                           decimalFormat.format(totalRate) +
                           " cache=" +
                           numberFormat.format(mb.getCacheMemoryUsage()) +
                           " inList=" +
                           numberFormat.format(inList.getSize()) +
                           " passes=" +
                           stats.getNEvictPasses() +
			   " sel=" +
			   numberFormat.format(stats.getNNodesSelected()) +
			   " scan=" +
			   numberFormat.format(stats.getNNodesScanned()) +
			   " evict=" +
			   numberFormat.format(stats.getNNodesExplicitlyEvicted()) +
			   " strip=" +
			   numberFormat.format(stats.getNBINsStripped()) +
                           " ckpt=" +
                           stats.getNCheckpoints() +
                           " clean=" +
                           stats.getNCleanerRuns() +
                           " cleanBacklog=" +
                           stats.getCleanerBacklog() +
                           " compress=" +
                           compressor.getBinRefQueueSize() +
                           " notRes/cmiss=" +
                           stats.getNNotResident() + "/" +
                           stats.getNCacheMiss());
        totalEvictPasses += stats.getNEvictPasses();
        totalSelected += stats.getNNodesSelected();
        totalScanned += stats.getNNodesScanned();
        totalExEvicted += stats.getNNodesExplicitlyEvicted();
        totalStripped += stats.getNBINsStripped();
        totalCkpts += stats.getNCheckpoints();
        totalCleaned += stats.getNCleanerRuns();
        totalNotResident += stats.getNNotResident();
        totalCacheMiss += stats.getNCacheMiss();
        System.out.println("id=" + threadId +
                           " " +  numberFormat.format(count) +
                           " totals:" + numberFormat.format(totalEvictPasses) +
                           " sel=" + numberFormat.format(totalSelected) +
                           " scan=" + numberFormat.format(totalScanned) +
                           " evict=" + numberFormat.format(totalExEvicted) +
                           " strip=" + numberFormat.format(totalStripped) +
                           " ckpt=" + numberFormat.format(totalCkpts) +
                           " clean=" + numberFormat.format(totalCleaned) +
                           " notRes=" + numberFormat.format(totalNotResident) +
                           " miss=" + numberFormat.format(totalCacheMiss));

        //summarizeINList(inList);
	//summarizeBtree(db);
	System.out.println("\n");
    }

    private void summarizeINList(INList inList)
	throws DatabaseException {

	int binCount = 0;
	int binBytes = 0;
	int inCount = 0;
	int inBytes = 0;
	
        Iterator iter = inList.iterator();

        while (iter.hasNext()) {
            IN theIN = (IN) iter.next();
            if (theIN instanceof BIN) {
                binCount++;
                //		    binBytes += theIN.computeMemorySize();
                BIN theBIN = (BIN) theIN;
                theBIN.evictLNs();
                binBytes += theIN.getBudgetedMemorySize();
                /*
                  for (int i = 0; i < theBIN.getNEntries(); i++) {
                  if (theBIN.getTarget(i) != null) {
                  lnCount++;
                  //	    lnBytes += theBIN.getTarget(i).
                  //	getMemorySizeIncludedByParent();
                  }
                  }
                */
            } else if (theIN instanceof IN) {
                inCount++;
                inBytes += theIN.getBudgetedMemorySize();
            } else {
                System.out.println("non-IN, non-BIN found on INList");
            }
        }


        double perBIN = ((double)binBytes)/binCount;
        double perIN = ((double)inBytes)/inCount;

	System.out.println("INList:" +
			   " nBINs: " + numberFormat.format(binCount) +
                           " binBytes (incl LNBytes): " + binBytes +
                           " perBin: " + numberFormat.format(perBIN) +
			   " nINs: " + numberFormat.format(inCount) +
                           " inBytes: " + inBytes +
                           " perIN: " + numberFormat.format(perIN));
        //" nLNs: " + numberFormat.format(lnCount));
        //   " lnBytes (incl in binBytes): " + lnBytes);
    }

    private void summarizeBtree(Database db)
	throws DatabaseException {

        StatsConfig dbStatsConfig = new StatsConfig();
	dbStatsConfig.setFast(false);
	BtreeStats stats = (BtreeStats) db.getStats(null);
	System.out.print("BTreeStats: BINCount=" +
			 stats.getBottomInternalNodeCount() +
			 " INCount=" +
			 stats.getInternalNodeCount() +
			 " LNCount=" +
			 stats.getLeafNodeCount() +
			 " treeDepth=" +
			 stats.getMainTreeMaxDepth() +
			 " ");
	summarizeINsByLevel("IN", stats.getINsByLevel());
    }

    private void summarizeINsByLevel(String msg, long[] insByLevel) {
	if (insByLevel != null) {
	    System.out.print(msg + " count by level: ");
	    for (int i = 0; i < insByLevel.length; i++) {
		long cnt = insByLevel[i];
		if (cnt != 0) {
		    System.out.print("[" + i + "," + insByLevel[i] + "]");
		}
	    }
	    System.out.print("   ");
	}
    }
}