GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Documentation
  • Privacy Statement
  • License Agreement
  • Contact Us

This view

  • Original page
  • New address

GeezerVison is showing docs.voltdb.com — 9.4. Modifying Both the Procedure and Interval

  • Volt Active Data
  • Developer Hub
  • Books
    • VoltDB Tutorial
    • Using VoltDB
    • VoltDB Guide to Performance and Customization
    • VoltDB Administrator's Guide
    • Volt Kubernetes Administrator's Guide
    • VoltDB Quick Reference
  • VoltDB V16
    • VoltDB V16
    • VoltDB V15.3 LTS
    • VoltDB V14.3 LTS
    • VoltDB V13.3 LTS
    • VoltDB V12.3 LTS
    • VoltDB V11.4
    • VoltDB V10.2
    • VoltDB V9.3
9.4. Modifying Both the Procedure and Interval

Guide to Performance and Customization

  • Preface▶
    • 1. Organization of this Manual
    • 2. Other Resources
  • 1. Introduction▶
    • 1.1. What Affects Performance?
    • 1.2. How to Use This Book
  • 2. Hello, World! Revisited▶
    • 2.1. Optimizing your Application for VoltDB
    • 2.2. Applying Hello World to a Practical Problem
    • 2.3. Partitioned vs. Replicated Tables
      • 2.3.1. Defining the Partitioning Column
      • 2.3.2. Creating the Stored Procedures
    • 2.4. Using Asynchronous Stored Procedure Calls
      • 2.4.1. Understanding Asynchronous Programming
      • 2.4.2. The Callback Procedure
      • 2.4.3. Making an Asynchronous Procedure Call
    • 2.5. Connecting to all Servers
    • 2.6. Putting it All Together
    • 2.7. Next Steps
  • 3. Understanding VoltDB Execution Plans▶
    • 3.1. How VoltDB Selects Execution Plans for Individual SQL Statements
    • 3.2. Understanding VoltDB Execution Plans
    • 3.3. Reading the Execution Plan and Optimizing Your SQL Statements
      • 3.3.1. Evaluating the Use of Indexes
      • 3.3.2. Evaluating the Table Order for Joins
  • 4. Using Indexes Effectively▶
    • 4.1. Basic Principles for Effective Indexing
    • 4.2. Defining Indexes
    • 4.3. The Goals for Effective Indexing
    • 4.4. How Indexes Work
    • 4.5. Summary
  • 5. Client2, A Modern Java Client Programming Interface (API)▶
    • 5.1. Configuring the Client
    • 5.2. Connecting to the Database
    • 5.3. Calling Procedures
      • 5.3.1. Handling Backpressure
      • 5.3.2. Handling Request Timeouts
      • 5.3.3. Defining Options on a Per-Call Basis
  • 6. Creating Flexible Schemas With JSON▶
    • 6.1. Using JSON Data Structures as VoltDB Content
    • 6.2. Querying JSON Data
    • 6.3. Updating JSON Data
    • 6.4. Indexing JSON Fields
    • 6.5. Summary: Using JSON in VoltDB
  • 7. Creating Geospatial Applications▶
    • 7.1. The Geospatial Datatypes
      • 7.1.1. The GEOGRAPHY_POINT Datatype
      • 7.1.2. The GEOGRAPHY Datatype
      • 7.1.3. Sizing GEOGRAPHY Columns
      • 7.1.4. How Geospatial Values are Interpreted
    • 7.2. Entering Geospatial Data
    • 7.3. Working With Geospatial Data
      • 7.3.1. Working With Locations
      • 7.3.2. Working With Regions
  • 8. Creating Custom Importers, Exporters, and Formatters▶
    • 8.1. Writing a Custom Exporter
      • 8.1.1. The Structure and Workflow of the Export Client
      • 8.1.2. How to Use Custom Properties to Configure the Client
      • 8.1.3. How to Compile and Install the Client
      • 8.1.4. How to Configure the Export Client
    • 8.2. Writing a Custom Importer
      • 8.2.1. Designing and Coding a Custom Importer
      • 8.2.2. Packaging and Installing a Custom Importer
      • 8.2.3. Configuring and Running a Custom Importer
    • 8.3. Writing a Custom Formatter
      • 8.3.1. The Structure of the Custom Formatter
      • 8.3.2. Compiling and Packaging Custom Formatter Bundles
      • 8.3.3. Installing and Invoking Custom Formatters
      • 8.3.4. Using Custom Formatters With the kafkaloader Utility
  • 9. Creating Custom Tasks▶
    • 9.1. Overview of How Custom Tasks Work
    • 9.2. Modifying the Procedure Call and Arguments
      • 9.2.1. Designing a Java Class That Implements ActionGenerator
      • 9.2.2. Compiling and Loading the Class into VoltDB
      • 9.2.3. Declaring the Task
    • 9.3. Modifying the Interval Between Invocations
      • 9.3.1. Designing a Java Class That Implements IntervalGenerator
      • 9.3.2. Compiling and Loading the Class into VoltDB
      • 9.3.3. Declaring the Task
    • 9.4. Modifying Both the Procedure and Interval
      • 9.4.1. Designing a Java Class That Implements ActionScheduler
      • 9.4.2. Compiling and Loading the Class into VoltDB
      • 9.4.3. Declaring the Task
  • 10. Using Compound Procedures▶
    • 10.1. How Compound Procedures Work
    • 10.2. Defining the Compound Procedure
    • 10.3. Compiling and Loading the Compound Procedure
    • 10.4. Declaring the Compound Procedure
    • 10.5. Invoking the Compound Procedure
    • 10.6. Handling Errors
    • 10.7. Managing Compound Procedures and System Resources
  • 11. Understanding Memory Usage▶
    • 11.1. How the Database Uses Memory
    • 11.2. Actions that Impact Memory Usage
    • 11.3. How the Database Manages Memory
    • 11.4. How Memory is Allocated and Deallocated
    • 11.5. Controlling How Memory is Allocated and Used
      • 11.5.1. Managing the Java Heap
      • 11.5.2. Controlling the Compaction Process for Table Data
    • 11.6. Understanding Memory Usage for Specific Applications
  • 12. Managing Time▶
    • 12.1. The Importance of Time
    • 12.2. Using NTP to Manage Time
      • 12.2.1. Basic Configuration
      • 12.2.2. Troubleshooting Issues with Time
      • 12.2.3. Correcting Common Problems with Time
      • 12.2.4. Example NTP Configuration
    • 12.3. Configuring NTP in a Hosted, Virtual, or Cloud Environment
      • 12.3.1. Considerations for Hosted Environments
      • 12.3.2. Considerations for Virtual and Cloud Environments

9.4. Modifying Both the Procedure and Interval

To allow full customization of the task — including the procedure, its arguments, and the interval between invocations — you create a custom task that implements the ActionScheduler interface. The custom task consists of the Java class you create, and the SQL statements to load and declare the task. At run time, for each invocation of the task, VoltDB uses the custom class to determine what procedure to invoke, what arguments to pass to the procedure, and how long to wait before invoking it.

Let's look at an example. The previous examples create tasks for purging old sessions from a database. But how can you tell that these tasks work without a real application? One way is to create a test database with tasks to emulate the expected workload, generating new sessions on an ongoing basis.

For our example, we want a task that generates sessions, but not so many the number of sessions created exceeds the number deleted. So our custom task needs to perform two actions:

  1. Check to see how many session records are in the database.

  2. If the task hasn't reached its target goal, generate up to 1,000 new sessions. Then repeat step 1.

In other words, we need two separate procedures: one to count the number of session records and another to insert a new session record. To count all session records in the database, the first procedure, CountSessions, must be multi-partitioned. (It also checks for the maximum value of the session ID so it can generate an incrementally unique ID.) But the second procedure, AddSession, can be partitioned since it is inserting into a partitioned table. This way the task reproduces the actions and performance of a running application.

CREATE PROCEDURE CountSessions AS
    SELECT COUNT(*), MAX(sessionID) FROM session;

CREATE PROCEDURE AddSession PARTITION ON TABLE SESSION COLUMN sessionID AS
    INSERT INTO session (sessionID,userID) VALUES(?,?);

The custom task will decide which procedure to invoke, and how long to wait between invocations, based on the results of the previous execution. There are many ways to do this, but for the sake of example, our custom task uses two separate callback methods: one to evaluate the results of the CountSessions procedure and one to evaluate the results of the AddSession procedure, as described in the next section.

9.4.1. Designing a Java Class That Implements ActionScheduler

The majority of the work of a custom class is performed by a Java class that implements a task interface; in this case, the ActionScheduler interface. It must be a static class whose constructor takes no arguments. The class must, at a minimum, declare or override three methods:

1

initialize()

The initialize() method is called first and receives a helper object inserted automatically by the subsystem that manages tasks, plus any parameters defined by the task definition in SQL. In our example there is one parameter in the task definition: the target number of records to create. So the initialize() method has a total of two arguments.

2

GetFirstInterval()

The getFirstInterval() method is called when the task starts; that is, when the task is first defined or when the database starts or resumes. The method must return a ScheduledAction object, which specifies the length of time to wait until the first execution of the task, a callback to invoke after the task runs, plus the name of the procedure and any arguments the procedure requires. In our example, we initialize the ScheduledAction object with no wait time (that is, an interval of zero), the callback for the CheckSessions procedure, and the procedure itself.

3

callback methods

After each iteration of the task, VoltDB invokes the specified callback procedure. In our example, there are two callback methods:

  • checkcallback — The task specifies this as the callback method to invoke after each iteration of the CheckSessions stored procedure. The callback checks the results for the number of session records. (it also saves the highest value of the session ID so it can generate an incrementally unique ID for each new record.) If the number of records is less than the goal, it schedules the AddSession procedure as the next task, specifying loadcallback() as the callback method. If the goal has been met, no more records need to be added so the callback backs off on the frequency (increasing the interval) and schedules the CheckSessions procedure again.

  • loadcallback — After each execution of the AddSession procedure, the callback reduces the batch size by one. If the batch is not complete, the callback reschedules the AddSession procedure, waiting 2 milliseconds. If the batch of inserts has been completed (that is, the batch size is down to zero), the callback schedules the CheckSessions procedure, specifying its callback method checkcallback() to see if there is now a full complement of session records.

Two things to note about this process are that if the session table is filled to the specified goal, the checkcallback uses the ability to customize the interval to reduce the frequency of checking — to minimize the impact on other transactions. Also, besides scheduling different stored procedures at different times, it passes different arguments as well, inserting a unique session ID and randomized user ID for each AddSession invocation.

Example 9.3, “Custom Task Implementing ActionScheduler” shows the completed example task class, with the key elements highlighted.

Example 9.3. Custom Task Implementing ActionScheduler

package mytasks;

import java.util.Random;

import java.util.concurrent.TimeUnit;
import org.voltdb.VoltTable;
import org.voltdb.client.ClientResponse;
import org.voltdb.task.*;

public  class LoadSessions implements ActionScheduler {

  private TaskHelper helper;
  private long batch, wait, nextid, goal;

  public void initialize(TaskHelper helper, long goal) {              1
    this.goal = goal;
    this.wait = 0;
  }

  public ScheduledAction getFirstScheduledAction() {                  2
    return ScheduledAction.procedureCall(0, TimeUnit.MILLISECONDS, 
       this::checkcallback, "CountSessions");
  }

  /*
   * Callbacks to handle the results of the check task 
   * and the load task
   */

  private ScheduledAction checkcallback(ActionResult result) {        3
  
    ClientResponse response = result.getResponse();
    VoltTable[] results = response.getResults();
    long recordcount = results[0].fetchRow(0).getLong(0);
    this.nextid = results[0].fetchRow(0).getLong(1);
    
    if (recordcount == 0) this.nextid = 0; /* start fresh*/
    this.batch = this.goal - recordcount;

     if (this.batch > 0) {
       /* Start loading data. Max batch size is 1,000 records */
       this.batch = (this.batch < 1000) ? this.batch : 1000;
       this.nextid++;
       return ScheduledAction.procedureCall(2, TimeUnit.MILLISECONDS, 
               this::loadcallback, "AddSession", 
               this.nextid,randomuser());
    } else {
       /* schedule the next check. */
       this.wait += 500;
       if (this.wait > 60000) this.wait = 60000;
       return ScheduledAction.procedureCall(this.wait, TimeUnit.MILLISECONDS, 
              this::checkcallback, "CountSessions");
    }
  }

  private ScheduledAction loadcallback(ActionResult result) {        3
    this.batch--;
    if (this.batch > 0 ) {
       /* Load next session */
       this.nextid++;
       return ScheduledAction.procedureCall(2, TimeUnit.MILLISECONDS, 
               this::loadcallback, "AddSession", 
               this.nextid,randomuser());
    } else {
       /* schedule the next check. */
       System.out.println(" Done.");
       this.wait = 0;
       return ScheduledAction.procedureCall(this.wait, TimeUnit.MILLISECONDS, 
            this::checkcallback, "CountSessions");
    }
  }
  
  private long randomuser() { return new Random().nextInt(1001); }

}

9.4.2. Compiling and Loading the Class into VoltDB

Once you complete your Java source code, you compile, debug, and package it into a JAR file the same way you compile and package stored procedures. You can package tasks, procedures, and other classes into a single or separate JARs depending on your application and operational needs. The following example compiles the Java classes in the src folder and packages it into the JAR file sessiontasks.jar:

$ javac -classpath "/opt/voltdb/voltdb/*" \
        -d ./obj  src/*.java
$ jar  cvf  sessiontasks.jar -C obj . 

You then load the classes from the JAR file into VoltDB using the sqlcmd LOAD CLASSES directive:

LOAD CLASSES sessiontasks.jar;

9.4.3. Declaring the Task

Once the custom class is loaded into the database, you can declare the task and start it running. You declare the task using the CREATE TASK statement, replacing both the ON SCHEDULE and PROCEDURE clauses with a single FROM CLASS clause specifying the classpath of your new class. In our example, the custom task also requires one argument: the target value for the maximum number of session records to create. The following statement creates the custom task with a goal of 10,000 records.

CREATE TASK loadsessions 
  FROM CLASS mytasks.LoadSessions WITH (10000)
  RUN ON DATABASE;

Note that the task is defined to RUN ON DATABASE. This means only one instance of the task is running at one time. However, the stored procedures will run as defined; that is, the CheckSessions procedure will run as a multi-partitioned procedure and each instance of AddSession will be executed on a specific partition based on the unique partition ID passed in as an argument at run-time.

The task starts as soon as it is declared, unless you include the DISABLE clause. Alternately, you can use the ALTER TASK statement to change the state of the task. For example, the following statement disables our newly created task:

3> ALTER TASK loadsessions DISABLE;
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.