File: SequenceGeneratorConcurrency.java

package info (click to toggle)
derby 10.14.2.0-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye
  • size: 78,896 kB
  • sloc: java: 691,930; sql: 42,686; xml: 20,511; sh: 3,373; sed: 96; makefile: 60
file content (400 lines) | stat: -rw-r--r-- 13,667 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
/*

Derby - Class org.apache.derbyTesting.perf.clients.SequenceGeneratorConcurrency

Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements.  See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License.  You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

*/

package org.apache.derbyTesting.perf.clients;

import java.io.PrintStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Random;

/**
 * <p>
 * Machinery to test the concurrency of sequence/identity generators.
 * </p>
 */
public class SequenceGeneratorConcurrency
{
    ///////////////////////////////////////////////////////////////////////////////////
    //
    // LOAD OPTIONS FOR THIS TEST
    //
    ///////////////////////////////////////////////////////////////////////////////////

    /**
     * <p>
     * Describes the load options specific to a run of the SequenceGeneratorConcurrency test.
     * </p>
     */
    public static final class LoadOptions
    {
        private int _numberOfGenerators;
        private int _tablesPerGenerator;
        private int _insertsPerTransaction;
        private boolean _runIdentityTest;
        private boolean _debugging;

        public LoadOptions()
        {
            _numberOfGenerators = Runner.getLoadOpt( "numberOfGenerators", 1 );
            _tablesPerGenerator = Runner.getLoadOpt( "tablesPerGenerator", 1 );
            _insertsPerTransaction = Runner.getLoadOpt( "insertsPerTransaction", 1 );
            //If no identityTest is specified, then do sequence testing.
            _runIdentityTest = ( Runner.getLoadOpt( "identityTest", 0 ) == 1);
            _debugging = ( Runner.getLoadOpt( "debugging", 0 ) == 1 );
        }

        /** Get the number of generators created by this test run */
        public int getNumberOfGenerators() { return _numberOfGenerators; }

        /** Get the number of tables created for each generator */
        public int getTablesPerGenerator() { return _tablesPerGenerator; }

        /** Get the number of inserts performed per transaction */
        public int getInsertsPerTransaction() { return _insertsPerTransaction; }

        /** Return whether we are in debugging mode */
        public boolean debugging() { return _debugging; }

        /** Return whether we are doing identity column testing */
        public boolean runIdentityTest() { return _runIdentityTest; }

        public String toString()
        {
            StringBuffer buffer = new StringBuffer();

            buffer.append( "LoadOptions( " );
            buffer.append( " generators = " + _numberOfGenerators );
            buffer.append( ", tablesPerGenerator = " + _tablesPerGenerator );
            buffer.append( ", insertsPerTransaction = " + _insertsPerTransaction );
            buffer.append( ", identityTest = " + _runIdentityTest );
            buffer.append( ", debugging = " + _debugging );
            buffer.append( " )" );

            return buffer.toString();
        }
        
    }

    ///////////////////////////////////////////////////////////////////////////////////
    //
    // DBFiller IMPLEMENTATION
    //
    ///////////////////////////////////////////////////////////////////////////////////

    /**
     * <p>
     * Create the schema necessary to support this test run.
     * </p>
     */
    public static final class Filler implements DBFiller
    {
        private LoadOptions _loadOptions;

        public Filler()
        {
            _loadOptions = new LoadOptions();
        }

        public void fill( Connection conn ) throws SQLException
        {
            int numberOfGenerators = _loadOptions.getNumberOfGenerators();
            int tablesPerGenerator = _loadOptions.getTablesPerGenerator();
            boolean runIdentityTest = _loadOptions.runIdentityTest();

            for ( int sequence = 0; sequence < numberOfGenerators; sequence++ )
            {
            	if (!runIdentityTest)
                    runDDL( conn, "create sequence " + makeSequenceName( sequence ) );

                for ( int table = 1; table <= tablesPerGenerator; table++ )
                {
                	if (runIdentityTest)
                        runDDL( conn, "create table " + makeTableName( sequence, table ) + "( a int, b int generated always as identity)" );
                	else
                        runDDL( conn, "create table " + makeTableName( sequence, table ) + "( a int )" );
                }
            }
        }

        /** Run a DDL statement */
        private void runDDL( Connection conn, String ddl ) throws SQLException
        {
            PreparedStatement ps = prepareStatement( conn, _loadOptions.debugging(), ddl );
            ps.execute();
            ps.close();
        }
    }

    ///////////////////////////////////////////////////////////////////////////////////
    //
    // Client IMPLEMENTATION
    //
    ///////////////////////////////////////////////////////////////////////////////////

    public static final class SGClient implements Client
    {
        private LoadOptions _loadOptions;
        private Connection _conn;
        private PreparedStatement _psArray[][];
        private Random _randomNumberGenerator;
        private int _clientNumber;
        private int _transactionCount;
        private int _errorCount = 0;
        private HashMap<String, int[]> _errorLog;

        private static int _clientCount = 0;

        // filled in at reporting time
        private static int _totalErrorCount = 0;
        private static int _totalTransactionCount = 0;

        public SGClient()
        {
            _clientNumber = _clientCount++;
            _transactionCount = 0;
            _errorLog = new HashMap<String, int[]>();
            _loadOptions = new LoadOptions();

            _psArray = new PreparedStatement[ _loadOptions.getNumberOfGenerators() ] [ _loadOptions.getTablesPerGenerator() + 1 ];
            _randomNumberGenerator = new Random();

            if ( _loadOptions.debugging() )
            {
                debugPrint( "Creating client " + _clientNumber + " with " + _loadOptions.toString() );
            }
        }

        /** Create the PreparedStatements needed by the test run. */
        public void init( Connection conn ) throws SQLException
        {
            _conn = conn;

            int numberOfGenerators = _loadOptions.getNumberOfGenerators();
            int tablesPerGenerator = _loadOptions.getTablesPerGenerator();
            boolean debugging = _loadOptions.debugging();
            boolean runIdentityTest = _loadOptions.runIdentityTest();

            for ( int sequence = 0; sequence < numberOfGenerators; sequence++ )
            {
                String sequenceName = makeSequenceName( sequence );

                for ( int table = 0; table <= tablesPerGenerator; table++ )
                {
                    String tableName = makeTableName( sequence, table );

                    PreparedStatement ps;
                    String valuesClause = "values ( next value for " + sequenceName + " )";

                    if ( table == 0 ){
                    	if(!runIdentityTest) 
                        	ps = prepareStatement( _conn, debugging, valuesClause );
                    	else
                        	ps = prepareStatement( _conn, debugging, "values (1)" );
                    }
                    else { 
                    	if(!runIdentityTest) 
                            ps = prepareStatement( _conn, debugging, "insert into " + tableName + "( a ) " + valuesClause ); 
                    	else
                        	ps = prepareStatement( _conn, debugging, "insert into " + tableName + "( a ) values(1)"); 
                	}
                    
                    _psArray[ sequence ][ table ] = ps;
                }
            }

            _conn.setAutoCommit( false );
        }

        /** A transaction performed by this thread */
        public void doWork() throws SQLException
        {
            int sequence = getPositiveRandomNumber() % _loadOptions.getNumberOfGenerators();
            int tablesPerGenerator = _loadOptions.getTablesPerGenerator();
            int table = tablesPerGenerator == 0 ? 0 : (getPositiveRandomNumber() % tablesPerGenerator) + 1;
            int insertsPerTransaction = _loadOptions.getInsertsPerTransaction();
            boolean debugging = _loadOptions.debugging();

            int rowNumber = 0;

            PreparedStatement ps = null;
            ResultSet rs = null;
            
            try {
                for ( ; rowNumber < insertsPerTransaction; rowNumber++ )
                {
                    rs = null;
                    ps = null;
                    
                    ps = _psArray[ sequence ][ table ];

                    if ( table == 0 )
                    {
                        rs = ps.executeQuery();
                        rs.next();

                        rs = close( rs, debugging );
                    }
                    else
                    {
                        ps.executeUpdate();
                    }
                    
                }
            }
            catch (Throwable t)
            {
                debugPrint
                    (
                     "Error on client " + _clientNumber +
                     " on sequence " + sequence +
                     " in transaction " + _transactionCount +
                     " on row " + rowNumber +
                     ": " + t.getMessage()
                     );

                addError( t );
                
                rs = close( rs, debugging );
                
                _conn.rollback();

                return;
            }

            _conn.commit();
            
            _transactionCount++;
        }

        private ResultSet close( ResultSet rs, boolean debugging )
        {
            try {
                if ( rs != null ) { rs.close(); }
            }
            catch (SQLException se)
            {
                if ( debugging ) { debugPrint( "Oops! " + se.getMessage() ); }
            }

            return null;
        }

        private PreparedStatement close( PreparedStatement ps, boolean debugging )
        {
            try {
                if ( ps != null ) { ps.close(); }
            }
            catch (SQLException se)
            {
                if ( debugging ) { debugPrint( "Oops! " + se.getMessage() ); }
            }

            return null;
        }

        private int getPositiveRandomNumber()
        {
            int raw = _randomNumberGenerator.nextInt();

            if ( raw < 0 ) { return -raw; }
            else { return raw; }
        }

        public void printReport(PrintStream out)
        {
            for (String key : _errorLog.keySet()) {
                int[] value = (int[]) _errorLog.get( key );

                String message = "    Client " + _clientNumber + " saw " + value[0] + " instances of this error: " + key;

                out.println( message );
            }

            _totalErrorCount += _errorCount;
            _totalTransactionCount += _transactionCount;

            // last client reports the totals
            if ( _clientNumber == ( _clientCount - 1 ) )
            {
                out.println( "\n" );
                out.println( _loadOptions.toString() );
                out.println( _totalErrorCount + " errors, including warmup phase." );
                out.println( _totalTransactionCount + " successful transactions, including warmup phase." );
            }
        }
        
        // error management

        /** Bump the error count for this problem */
        private void addError( Throwable t )
        {
            _errorCount++;
            
            String key = t.getClass().getName() + ": " + t.getMessage();
            int[] value = _errorLog.get( key );

            if ( value != null ) { value[ 0 ] = value[ 0 ] + 1; }
            else
            {
                _errorLog.put( key, new int[] { 1 } );
            }
        }
    }

    ///////////////////////////////////////////////////////////////////////////////////
    //
    // UTILITY METHODS
    //
    ///////////////////////////////////////////////////////////////////////////////////

    /** make the name of a sequence */
    public static String makeSequenceName( int sequence )
    { return "seq_" + sequence; }
    
    /** make the name of a table */
    public static String makeTableName( int sequence, int table )
    { return "t_" + sequence + "_" + table; }

    public static PreparedStatement prepareStatement
        ( Connection conn, boolean debugging, String text ) throws SQLException
    {
        if ( debugging ) { debugPrint( text ); }

        return conn.prepareStatement( text );
    }
    
    public static void debugPrint( String text )
    {
        print( "DEBUG: " + text );
    }

    public static void print( String text )
    {
        System.out.println( text );
    }

}