Przeglądaj źródła

Implement batch updating in PO (plain old) Servlets (#2597)

Update Jackson library to latest
Radoslav Petrov 8 lat temu
rodzic
commit
547ab2dae1

+ 2 - 3
frameworks/Java/servlet/benchmark_config.json

@@ -40,8 +40,7 @@
       "os": "Linux",
       "database_os": "Linux",
       "display_name": "servlet",
-      "notes": "",
-      "versus": "servlet"
+      "notes": ""
     },
     "postgres-raw": {
       "setup_file": "setup_postgresql",
@@ -63,7 +62,7 @@
       "database_os": "Linux",
       "display_name": "servlet",
       "notes": "",
-      "versus": "servlet"
+      "versus": "servlet-raw"
     }
   }]
 }

+ 79 - 77
frameworks/Java/servlet/pom.xml

@@ -1,86 +1,88 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
-    <modelVersion>4.0.0</modelVersion>
-    <groupId>hello.world</groupId>
-    <artifactId>world</artifactId>
-    <name>Servlet</name>
-    <packaging>war</packaging>
-    <version>1.0.0-BUILD-SNAPSHOT</version>
-    <properties>
-        <java-version>1.7</java-version>
-    </properties>
-    <dependencies>
-        <dependency>
-            <groupId>mysql</groupId>
-            <artifactId>mysql-connector-java</artifactId>
-            <version>5.1.38</version>
-        </dependency>
+	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+	<modelVersion>4.0.0</modelVersion>
+	<groupId>hello.world</groupId>
+	<artifactId>world</artifactId>
+	<name>Servlet</name>
+	<packaging>war</packaging>
+	<version>1.0.0-BUILD-SNAPSHOT</version>
+	<properties>
+		<java-version>1.8</java-version>
+	</properties>
+	<dependencies>
+		<dependency>
+			<groupId>mysql</groupId>
+			<artifactId>mysql-connector-java</artifactId>
+			<version>5.1.38</version>
+		</dependency>
 
-	<dependency>
-	    <groupId>org.postgresql</groupId>
-	    <artifactId>postgresql</artifactId>
-	    <version>9.4.1208</version>
-	</dependency>
-            
+		<dependency>
+			<groupId>org.postgresql</groupId>
+			<artifactId>postgresql</artifactId>
+			<version>9.4.1208</version>
+		</dependency>
 
-        <dependency>
-            <groupId>com.fasterxml.jackson.core</groupId>
-            <artifactId>jackson-databind</artifactId>
-            <version>2.3.0</version>
-        </dependency>
 
-	<dependency>
-	  <groupId>jstl</groupId>
-	  <artifactId>jstl</artifactId>
-	  <version>1.2</version>
-	</dependency>
-        <!-- @Inject -->
-        <dependency>
-            <groupId>javax.inject</groupId>
-            <artifactId>javax.inject</artifactId>
-            <version>1</version>
-        </dependency>
- 
-        <!-- Servlet -->
-        <dependency>
-            <groupId>javax.servlet</groupId>
-            <artifactId>servlet-api</artifactId>
-            <version>2.5</version>
-            <scope>provided</scope>
-        </dependency>
+		<dependency>
+			<groupId>com.fasterxml.jackson.core</groupId>
+			<artifactId>jackson-databind</artifactId>
+			<version>2.8.7</version>
+		</dependency>
 
-        <!-- Apache Commons Lang -->
-        <dependency>
-          	<groupId>org.apache.commons</groupId>
-            <artifactId>commons-lang3</artifactId>
-            <version>3.1</version>
-        </dependency>
+		<dependency>
+			<groupId>jstl</groupId>
+			<artifactId>jstl</artifactId>
+			<version>1.2</version>
+		</dependency>
+		<!-- @Inject -->
+		<dependency>
+			<groupId>javax.inject</groupId>
+			<artifactId>javax.inject</artifactId>
+			<version>1</version>
+		</dependency>
 
-    </dependencies>
+		<!-- Servlet -->
+		<dependency>
+			<groupId>javax.servlet</groupId>
+			<artifactId>servlet-api</artifactId>
+			<version>2.5</version>
+			<scope>provided</scope>
+		</dependency>
 
-    <build>
-        <plugins>
-            <plugin>
-                <groupId>org.apache.maven.plugins</groupId>
-                <artifactId>maven-compiler-plugin</artifactId>
-                <configuration>
-                    <source>${java-version}</source>
-                    <target>${java-version}</target>
-                </configuration>
-            </plugin>
-            <plugin>
-                <groupId>org.apache.maven.plugins</groupId>
-                <artifactId>maven-war-plugin</artifactId>
-                <configuration>
-                    <warName>servlet</warName>
-                </configuration>
-            </plugin>
-            <plugin>
-                <groupId>org.codehaus.mojo</groupId>
-                <artifactId>tomcat-maven-plugin</artifactId>
-                <version>1.1</version>
-            </plugin>
-        </plugins>
-    </build>
+		<!-- Apache Commons Lang -->
+		<dependency>
+			<groupId>org.apache.commons</groupId>
+			<artifactId>commons-lang3</artifactId>
+			<version>3.5</version>
+		</dependency>
+
+	</dependencies>
+
+	<build>
+		<plugins>
+			<plugin>
+				<groupId>org.apache.maven.plugins</groupId>
+				<artifactId>maven-compiler-plugin</artifactId>
+				<configuration>
+					<source>${java-version}</source>
+					<target>${java-version}</target>
+					<optimize>true</optimize>
+					<debug>false</debug>
+				</configuration>
+			</plugin>
+			<plugin>
+				<groupId>org.apache.maven.plugins</groupId>
+				<artifactId>maven-war-plugin</artifactId>
+				<configuration>
+					<warName>servlet</warName>
+				</configuration>
+			</plugin>
+			<plugin>
+				<groupId>org.codehaus.mojo</groupId>
+				<artifactId>tomcat-maven-plugin</artifactId>
+				<version>1.1</version>
+			</plugin>
+		</plugins>
+	</build>
 </project>

+ 25 - 22
frameworks/Java/servlet/src/main/java/hello/PlaintextServlet.java

@@ -1,33 +1,36 @@
 package hello;
 
-import java.io.*;
+import java.io.IOException;
 
-import javax.servlet.*;
-import javax.servlet.http.*;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
 
 /**
  * Plaintext rendering Test
  */
 @SuppressWarnings("serial")
-public class PlaintextServlet extends HttpServlet
-{
+public class PlaintextServlet extends HttpServlet {
+	private static final String MESSAGE = "Hello, World!";
+	private static final byte[] buffer;
 
-  @Override
-  protected void doGet(HttpServletRequest req, HttpServletResponse res)
-      throws ServletException, IOException
-  {
-    // Set content type to text/plain.
-    res.setHeader(Common.HEADER_CONTENT_TYPE, Common.CONTENT_TYPE_TEXT);
+	static {
+		try {
+			buffer = MESSAGE.getBytes("US-ASCII");
+		} catch (Exception e) {
+			throw new RuntimeException(e);
+		}
+	}
+
+	@Override
+	protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
+			IOException {
+		// Set content type to text/plain.
+		res.setContentType(Common.CONTENT_TYPE_TEXT);
+
+		// Write plaintext "Hello, World!" to the response.
+		res.getOutputStream().write(buffer);
+	}
 
-    // Write plaintext "Hello, World!" to the response.
-    try
-    {
-      res.getWriter().write("Hello, World!");
-    }
-    catch (IOException ioe) 
-    {
-      // do nothing
-    }
-  }
-  
 }

+ 86 - 96
frameworks/Java/servlet/src/main/java/hello/PostgresUpdateServlet.java

@@ -1,109 +1,99 @@
 package hello;
 
-import java.io.*;
-import java.sql.*;
-import java.util.*;
-import java.util.concurrent.*;
+import java.io.IOException;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.Random;
+import java.util.concurrent.ThreadLocalRandom;
 
-import javax.annotation.*;
-import javax.servlet.*;
-import javax.servlet.http.*;
-import javax.sql.*;
+import javax.annotation.Resource;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.sql.DataSource;
 
 /**
  * Database connectivity (with a Servlet-container managed pool) test.
  */
 @SuppressWarnings("serial")
-public class PostgresUpdateServlet extends HttpServlet
-{
-  // Database details.
-  private static final String DB_QUERY      = "SELECT * FROM World WHERE id = ?";
-  private static final String UPDATE_QUERY  = "UPDATE World SET randomNumber = ? WHERE id = ?";
-  private static final int    DB_ROWS       = 10000;
+public class PostgresUpdateServlet extends HttpServlet {
+	// Database details.
+	private static final String DB_QUERY = "SELECT * FROM World WHERE id = ?";
+	private static final String UPDATE_QUERY = "UPDATE World SET randomNumber = ? WHERE id = ?";
+	private static final int DB_ROWS = 10000;
 
-  // Database connection pool.
-  @Resource(name="jdbc/postgres_hello_world")
-  private DataSource postgresDataSource;
-    
-  @Override
-  protected void doGet(HttpServletRequest req, HttpServletResponse res)
-      throws ServletException, IOException
-  {
-    // Set content type to JSON
-    res.setHeader(Common.HEADER_CONTENT_TYPE, Common.CONTENT_TYPE_JSON);
+	// Database connection pool.
+	@Resource(name = "jdbc/postgres_hello_world")
+	private DataSource postgresDataSource;
 
-    // Reference the data source.
-    final DataSource source = postgresDataSource;
-    
-    // Get the count of queries to run.
-    int count = 1;
-    try
-    {
-      count = Integer.parseInt(req.getParameter("queries"));
-      
-      // Bounds check.
-      if (count > 500)
-      {
-        count = 500;
-      }
-      if (count < 1)
-      {
-        count = 1;
-      }
-    }
-    catch (NumberFormatException nfexc)
-    {
-      // Do nothing.
-    }
+	@Override
+	protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
+			IOException {
+		// Set content type to JSON
+		res.setHeader(Common.HEADER_CONTENT_TYPE, Common.CONTENT_TYPE_JSON);
 
-    // Fetch some rows from the database.
-    final World[] worlds = new World[count];
-    final Random random = ThreadLocalRandom.current();
-    
-    try (Connection conn = source.getConnection())
-    {
-      try (PreparedStatement statement = conn.prepareStatement(DB_QUERY, 
-          ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY))
-      {
-        // Run the query the number of times requested.
-        for (int i = 0; i < count; i++)
-        {
-          final int id = random.nextInt(DB_ROWS) + 1;
-          statement.setInt(1, id);
-          
-          try (ResultSet results = statement.executeQuery())
-          {
-            if (results.next())
-            {
-              worlds[i] = new World(id, results.getInt("randomNumber"));
+		// Reference the data source.
+		final DataSource source = postgresDataSource;
 
-              // Update row
-              try (PreparedStatement statement2 = conn.prepareStatement(UPDATE_QUERY))
-              {
-		worlds[i].setRandomNumber(random.nextInt(DB_ROWS) + 1);
-                statement2.setInt(1, worlds[i].getRandomNumber());
-                statement2.setInt(2, id);
+		// Get the count of queries to run.
+		int count = 1;
+		try {
+			count = Integer.parseInt(req.getParameter("queries"));
 
-                statement2.execute();
-              }
-            }
-          }
-        }
-      }
-    }
-    catch (SQLException sqlex)
-    {
-      System.err.println("SQL Exception: " + sqlex);
-    }
-    
-    // Write JSON encoded message to the response.
-    try
-    {
-      Common.MAPPER.writeValue(res.getOutputStream(), worlds);
-    }
-    catch (IOException ioe) 
-    {
-      // do nothing
-    }
-  }
-}
+			// Bounds check.
+			if (count > 500) {
+				count = 500;
+			}
+			if (count < 1) {
+				count = 1;
+			}
+		} catch (NumberFormatException nfexc) {
+			// Do nothing.
+		}
+
+		// Fetch some rows from the database.
+		final World[] worlds = new World[count];
+		final Random random = ThreadLocalRandom.current();
+
+		try (Connection conn = source.getConnection()) {
+			try (PreparedStatement statement = conn.prepareStatement(DB_QUERY,
+					ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
+					PreparedStatement statement2 = conn.prepareStatement(UPDATE_QUERY,
+							ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)) {
+				// Run the query the number of times requested.
+				for (int i = 0; i < count; i++) {
+					final int id = random.nextInt(DB_ROWS) + 1;
+					statement.setInt(1, id);
+
+					try (ResultSet results = statement.executeQuery()) {
+						if (results.next()) {
+							worlds[i] = new World(id, results.getInt("randomNumber"));
+
+							// Update row
+							worlds[i].setRandomNumber(random.nextInt(DB_ROWS) + 1);
+							statement2.setInt(1, worlds[i].getRandomNumber());
+							statement2.setInt(2, id);
+
+							// Add update statement to batch update
+							statement2.addBatch();
+						}
+					}
+				}
+				// Execute batch update
+				statement2.executeBatch();
+			}
+		} catch (SQLException sqlex) {
+			System.err.println("SQL Exception: " + sqlex);
+		}
+
+		// Write JSON encoded message to the response.
+		try {
+			Common.MAPPER.writeValue(res.getOutputStream(), worlds);
+		} catch (IOException ioe) {
+			// do nothing
+		}
+	}
+}

+ 86 - 96
frameworks/Java/servlet/src/main/java/hello/UpdateServlet.java

@@ -1,109 +1,99 @@
 package hello;
 
-import java.io.*;
-import java.sql.*;
-import java.util.*;
-import java.util.concurrent.*;
+import java.io.IOException;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.Random;
+import java.util.concurrent.ThreadLocalRandom;
 
-import javax.annotation.*;
-import javax.servlet.*;
-import javax.servlet.http.*;
-import javax.sql.*;
+import javax.annotation.Resource;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.sql.DataSource;
 
 /**
  * Database connectivity (with a Servlet-container managed pool) test.
  */
 @SuppressWarnings("serial")
-public class UpdateServlet extends HttpServlet
-{
-  // Database details.
-  private static final String DB_QUERY      = "SELECT * FROM World WHERE id = ?";
-  private static final String UPDATE_QUERY  = "UPDATE World SET randomNumber = ? WHERE id = ?";
-  private static final int    DB_ROWS       = 10000;
+public class UpdateServlet extends HttpServlet {
+	// Database details.
+	private static final String DB_QUERY = "SELECT * FROM World WHERE id = ?";
+	private static final String UPDATE_QUERY = "UPDATE World SET randomNumber = ? WHERE id = ?";
+	private static final int DB_ROWS = 10000;
 
-  // Database connection pool.
-  @Resource(name="jdbc/hello_world")
-  private DataSource mysqlDataSource;
-    
-  @Override
-  protected void doGet(HttpServletRequest req, HttpServletResponse res)
-      throws ServletException, IOException
-  {
-    // Set content type to JSON
-    res.setHeader(Common.HEADER_CONTENT_TYPE, Common.CONTENT_TYPE_JSON);
+	// Database connection pool.
+	@Resource(name = "jdbc/hello_world")
+	private DataSource mysqlDataSource;
 
-    // Reference the data source.
-    final DataSource source = mysqlDataSource;
-    
-    // Get the count of queries to run.
-    int count = 1;
-    try
-    {
-      count = Integer.parseInt(req.getParameter("queries"));
-      
-      // Bounds check.
-      if (count > 500)
-      {
-        count = 500;
-      }
-      if (count < 1)
-      {
-        count = 1;
-      }
-    }
-    catch (NumberFormatException nfexc)
-    {
-      // Do nothing.
-    }
+	@Override
+	protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
+			IOException {
+		// Set content type to JSON
+		res.setHeader(Common.HEADER_CONTENT_TYPE, Common.CONTENT_TYPE_JSON);
 
-    // Fetch some rows from the database.
-    final World[] worlds = new World[count];
-    final Random random = ThreadLocalRandom.current();
-    
-    try (Connection conn = source.getConnection())
-    {
-      try (PreparedStatement statement = conn.prepareStatement(DB_QUERY, 
-          ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY))
-      {
-        // Run the query the number of times requested.
-        for (int i = 0; i < count; i++)
-        {
-          final int id = random.nextInt(DB_ROWS) + 1;
-          statement.setInt(1, id);
-          
-          try (ResultSet results = statement.executeQuery())
-          {
-            if (results.next())
-            {
-              worlds[i] = new World(id, results.getInt("randomNumber"));
+		// Reference the data source.
+		final DataSource source = mysqlDataSource;
 
-              // Update row
-              try (PreparedStatement statement2 = conn.prepareStatement(UPDATE_QUERY))
-              {
-		worlds[i].setRandomNumber(random.nextInt(DB_ROWS) + 1);
-                statement2.setInt(1, worlds[i].getRandomNumber());
-                statement2.setInt(2, id);
+		// Get the count of queries to run.
+		int count = 1;
+		try {
+			count = Integer.parseInt(req.getParameter("queries"));
 
-                statement2.execute();
-              }
-            }
-          }
-        }
-      }
-    }
-    catch (SQLException sqlex)
-    {
-      System.err.println("SQL Exception: " + sqlex);
-    }
-    
-    // Write JSON encoded message to the response.
-    try
-    {
-      Common.MAPPER.writeValue(res.getOutputStream(), worlds);
-    }
-    catch (IOException ioe) 
-    {
-      // do nothing
-    }
-  }
-}
+			// Bounds check.
+			if (count > 500) {
+				count = 500;
+			}
+			if (count < 1) {
+				count = 1;
+			}
+		} catch (NumberFormatException nfexc) {
+			// Do nothing.
+		}
+
+		// Fetch some rows from the database.
+		final World[] worlds = new World[count];
+		final Random random = ThreadLocalRandom.current();
+
+		try (Connection conn = source.getConnection()) {
+			try (PreparedStatement statement = conn.prepareStatement(DB_QUERY,
+					ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
+					PreparedStatement statement2 = conn.prepareStatement(UPDATE_QUERY,
+							ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)) {
+				// Run the query the number of times requested.
+				for (int i = 0; i < count; i++) {
+					final int id = random.nextInt(DB_ROWS) + 1;
+					statement.setInt(1, id);
+
+					try (ResultSet results = statement.executeQuery()) {
+						if (results.next()) {
+							worlds[i] = new World(id, results.getInt("randomNumber"));
+
+							// Update row
+							worlds[i].setRandomNumber(random.nextInt(DB_ROWS) + 1);
+							statement2.setInt(1, worlds[i].getRandomNumber());
+							statement2.setInt(2, id);
+
+							// Add update statement to batch update
+							statement2.addBatch();
+						}
+					}
+				}
+				// Execute batch update
+				statement2.executeBatch();
+			}
+		} catch (SQLException sqlex) {
+			System.err.println("SQL Exception: " + sqlex);
+		}
+
+		// Write JSON encoded message to the response.
+		try {
+			Common.MAPPER.writeValue(res.getOutputStream(), worlds);
+		} catch (IOException ioe) {
+			// do nothing
+		}
+	}
+}