Monday, August 19, 2013

Server Side Sessions vs Client Cookie Sessions

If we were to strictly follow the REST model, we should not store client state on the server, including sessions.  Since I am starting a new project, I thought I would take a moment to evaluate the pros and cons of server side sessions vs client cookie sessions.

1) Scalability
One the major arguments against server side sessions is that it does not scale.  Using the traditional Java model, session are stored in memory.  Thus, with lots of users and large sessions, one can run out of  memory.    On the other hand, in the PHP world, server side sessions are typically stored in a  file. While this will not run into a memory problem, this will require frequent disk read and writes at each request.    Both of these server side session models (Java and PHP) are thought to not scale well.  Lets take a closer look...

How much memory does a Java session take?  

This is a crucial question.  If Java sessions take lots of memory, then we know this will not scale.  However, as it turns out a Java session takes very little memory, in fact on my machine, a single session only takes 1.67 KB (of course filled with more data, that number will be higher).  That means that we can store sessions for 10K users in a mere 16.3 MB.  If we keep the information in our sessions small, memory is really not too much of an issue.  

But what if we have lots of sessions or larger sessions? 

To solve this problem, Tomcat has a configuration that allows a hybrid appraoch between memory sessions and disk based sessions.  Using this model, sessions are stored in memory, but then serialized to disk after a configurable timeout.  If needed again, the sessions are brought back into memory. This option provides rather good scalability.  The sessions  are released from memory after a period of inactivity, and do not need to be read from disk each time. Using this model, I do not see most web apps suffering from a scalability issue stemming from high memory or frequent disk access.  

2) Security
Using server side sessions, all session data is stored on the server side.  While it is possible to secure sessions in the cookie, it is harder to get right.  Having the session information on server makes it harder for users to manually change data.

3) Performance
Server side sessions are simply faster: not only is there less network traffic, there is also less server side computation.   However, if one were to place session in the cookie,  extra server side computation is required to de-serialize the session, validate the session, and then re-serialize back into the cookie.  Granted, this computation could be considered negligible, it is worth pointing out that expensive cookie encryption could create overhead.

4) Flexibility
Using client cookie sessions, you have strict limitations: only 4K of string data.  In most situations, this will work fine.  In fact, if one is putting more than 4K in a session, they are likely abusing their sessions (which is all to common in many Java frameworks).  However, occasionally you do need to add more than 4K of data, and at times it is convenient to store non string data.  Server side sessions provide the flexibility to do so.

5) Load Balancing
Perhaps the greatest feature of client cookie sessions is that load balancing is a breeze.  Since no state is stored on the server, it does not matter which server handles the request.  

On the other hand, using server side sessions, once a session is created the same server must handle each subsequent request.  However, in most situations, this is really a non issue since every load balancer supports a mechanism to forward requests in a sticky manner, either via an ip table or cookie.  Things do get more tricky when you need to take a server off line, as you might need to "drain" a server of its sessions.  Yes, this is annoying, but should only need to occur occasionally.  (and this annoyance will be only be one small component  within a larger and more complex process of updating apps on the fly, a complication which exists regardless of the type of session).

Conclusion
In this post we briefly looked at some of the pros and cons of storing session data on the server or in client cookies.  While cookies do provide some excellent benefits, particularly in load balancing, I think that server session will still work fine in most types of apps.  To each their own!

For my current project, I am going to continue using the tomcat's hybrid memory-disk option.  It provides a scalable, flexible, and secure solution for sever side sessions.

Tuesday, July 30, 2013

Digital Ocean announces new data center

Digital Ocean just accouned a new data center in NYC.  You can read about it here.

They say that "this new datacenter brings DigitalOcean even closer to rolling out private networking for our customers, which will premiere in NY2!"  

Does this mean that Digital Ocean will soon have free transfer between private IPs?  If so this, is great and will add a feature that is currently missing from Digital Ocean's stack.

Digital Ocean vs Linode

Over the past few years I have ran a number of web apps out of Linode's VPS.  I truly could not be more happy with Linode: great product, great service, fair pricing, excellent features, etc.

However, I am not building my new project on Linode, but on a newer VPS: Digital Ocean.   Here are some thoughts on the two VPSs.

Pro Digital Ocean

1) Price:  You can just can't beat Digital Ocean's price .  You can spin up their cheapest droplet for only $5, with 512 Ram, 20GB SSD, 1TB transfer.  Nice!   On the other hand, the cheapest Linode server is $20.  Clearly the $20 Llnode is better than the $5 Digital Ocean.  But with Digital Ocean you can get up and running for less money.  You can check out their price comparison chart.

2) Billing per hour:  Unlike Linode, at Digital Ocean you are only billed per hour that the droplet is running.  This model makes it easier (and less risk) to try out  different setups.   However, at Linode, you are charged for a full month.  If you then cancel mid month, you are given a prorated credit.  So, the situation at Linode is not too bad either, but does not lead as much to developer experimentation.

3) Transfer Speed:  A number of people in the past have complained about Digital Ocean's transfer speed.   However, in my simple tests, Digital Ocean actually transferred slightly faster than Linode.  I tested this each day for over 2 weeks, and Digital Ocean was always better.  I know there could be other mitigating factors, but this is a nod towards Digital Ocean!


Pro Linode

1) Great Reputation - Linode has been around for years and they will stick around.  They will not go belly up any time soon.  On the other hand, Digital Ocean is a newcomer.  Can they compete in the long run?  Will I need to find another VPS after Digital Ocean goes out of business?

2)  Web Interface - Linode's web interface is much better than Digital Ocean's.  Creating nodes and configuring DNS is much more feature rich on Linode.

3) Free Transfer on Private IPs - At Linode, when you transfer data between nodes, there is no transfer costs.   However, at Digital Ocean, you pay the same cost when you transfer between nodes.  So, with Digital Ocean, if you put a database on another server, you will have to pay for each data transfer.  The same goes with a load balancer.  Digital Ocean is great if your app is on a single server, but not so great if your app is spread among sever intercommunicating servers.  Big win for Linode! 

4) Node Balancer - Linode offers setup load balancer for $20 a month.  This is a great service and there is no Digital Ocean equivalent.  Again, Linode shines when you need to scale your app beyond one server.

5) Pooled Bandwith - At Linode, your transfer limits are placed in a pool and shared among all nodes.  Thus, if your image server goes over its limit, it will simply access the transfer limit of the entire pool.  However, at Digital Ocean, there is currently no pooled bandwidth, and it is at best confusing if they will ever offer pooled bandwidth.  Again, Linode offers better services for architectures that might use more than one server.

Summary

Both Digital Ocean and Linode are great VPSs.  If you do not anticpate your server neededing more than one server, Digital Ocean will work great.  However, if you anticpate an server that needs more than one coupled server, than Linode will likely be the better option.

As for me, I am going with Digital Ocean for my new project.  We will see how it pans out!

Saturday, March 16, 2013

Quercus PHP: interpreted vs compiled

The good folks at Caucho were nice enough to send me a trial key for Quercus PHP Professional, so I gave it a spin this morning.

Quercus PHP is an implementation of PHP that runs on the JVM.  The open source version runs in interpreted mode, while the Pro version compiles the PHP to Java byte code.  The Pro version is not free, but costs $99 a year for a license.

Three Ways to Run Quercus PHP:  As I see it, there are 3 ways to run Querucs, and your choice would depend on your use case and needs.

A) Compiled Mode -  Compiled mode is only available in Quercus Pro ($99), but this will give you the fastest speed.  The PHP script is compiled to Java classes, which yields not only fast PHP execution, but also leads to high performance integration with existing Java code.  The only downside of this mode is that static strings are stored in the PermGen space.  This is not necessarily a bad thing and this works the same way as JSPs, but it just something to be aware of when you are allocating space and re-deploying apps.

B) Interpreted Mode - In this mode, the PHP pages are interpreted at each request.  This is still very fast, and very similar in speed to mod_php without APC.  In this mode, the PHP file is cached, so there is no need to re-read the PHP from disk IO.  You can adjust the size of the PHP page cache.

C) Interpreted with No Page Cache - This mode is the same as the above, except it removes the page cache of the PHP file.  This mode is very similar to mod_php in that each PHP file is re-read from disk at each request.  Most people would want a PHP page cache, but there are times when you may not want it because it will consume extra memory to keep those pages in the cache.  On a memory restricted sites, with lots of different PHP pages in which each page (in of itself) is accessed rarely, you may want to disable the page cache.

Quick Performance Test

I ran a quick benchmark to see how the different Querucs modes perform.  I grabbed a PHP benchmark from this site.  This is a rather long running script, so it does not measure requests per second, but rather the time it takes to execute and entire script.  Tomcat 7 was used as the Java server.  I ran the scripts a number of times and averaged the results:

quercus compiled - 3247 ms
quercus interpreted  - 7540 ms
quercus interpreted no page-cache -7798 ms
apache mod_php - 9088 ms
apache apc  - 9159ms

As we can see Quercus in compiled mode is almost 3 times faster than Apache mod_php, and Quercus interpreted is a bit faster as well.

Since this is a long running script, the page cache did not really help the interpreted mode of Quercus.  Similarly APC did not help mod_php, because the compile time is a small fraction of the running time.

We should not conclude too much from this quick test, but it seems to be in line with some of the results found on the official Quercus page.

Saturday, March 9, 2013

MVC using Servlet with a Quercus PHP view

In this short post I will briefly explain how to create an MVC system that uses a Java servlet as the control and model, and a PHP page as the view.  We will use Quercus PHP, the great implementation of PHP that runs inside the JVM.  This tutorial will assume that you know how to setup and use both Java sevlets and Quercus (simply google them if you do not know, or send me a note).

This post will build off of the classic Servlet/JSP MVC examples, as seen in tutorials like this.  But instead of using a JSP to view the model, we will use PHP.  So, really this just boils down to how you can pass a Java object to PHP.

Lets start with a simple servlet that contains this code in the process request:
            request.setAttribute("message", "hello from java to php");
            request.setAttribute("number", 100);
            RequestDispatcher dispatcher;
            dispatcher=request.getRequestDispatcher("/view.php");
            dispatcher.forward(request, response);
Ok, this code should be familiar, we simply place two objects inside the request and the forward the request dispatcher to a PHP page called 'vew.php' (instead of a jsp page).  Now lets look at the PHP code.

The first thing we want to do in view.php is grab the Java request object, so we can grab the objects we placed in the request.  Quercus provides the PHP function quercus_servlet_request() to do just this.  Then I add a function to make it easier to get the object attributes out of the request.  It is a good idea to put this code in a global include:
        <?php
             $request = quercus_servlet_request();
             function getAttribute($key) {
                  global $request;
                  return $request->getAttribute($key);
             }

         ?>

Now, within PHP we can call the above function to get the Java objects, and use PHP as the view component of the MVC. Piece of cake!
       <?php
            $message = getAttribute("message");
            echo "message = ".$message."<br>";
           $number = getAttribute("number");
           echo "number = ".$number;
       ?>

Friday, March 8, 2013

Tips for Unity3D mobile development

There have been several articles written how to optimize Unity3d for mobile development.  Most of those articles focus on draw calls, polygon reduction, texture atlases, etc.  Those are all great topics, but I wanted to pass on a few more tips.  Enjoy!


1) Favor cookie-cut geometry over cookie-cut textures.

As it is well known, mobile devices are not optimized for handling textures with transparencies.  Instead of having a cookie-cut alpha channel on a textures, it is often possible to achieve similar results by simply increasing the geometry. 

For example, if you needed to create a "star" you could use a 2d plane textured map with a an alpha-blended or cut-out image of a star.  Alternatively, you could model the outline shape simple star (a few more polygons will do the trick) and then apply a non-transparent texture.  In this second way, the geometry provides the cookie-cut.  While this technique is not appropriate for all cases, it does often work well and leads to higher performance, because mobile devices are optimized for polygons not transparent textures.


2) Use a texture atlas for in game text.

Never use text GUI elements during gamlay, and try to avoid Text3D/Mesh (as they use transparencies).  Instead, when possible, using an opaque texture atlas.  For example, in our recent game we wanted to display the number of coins the user has collected.  So we created this texture atlas.

By dynamcailly moving the UV coridatnes on a set of rectangle polygons, we were able to achieve much faster frame rates than if we were using text3d or text meshes.  It is a bit of work to set this up, but it is worth it (assuming you do not need transparent text).   To change the UV coordinates:

        // Grab the mesh first
        Mesh mesh =gameObject.GetComponent<MeshFilter> ().mesh. 

       //Create an array of uvs... set them to be whatever you want
       Vector2[] uvs = new Vector2[4];
      
      // Apply the UVs to your mesh
      mesh.uv = uvs;


3) Avoid objects GameObjects with attached Behavior scripts

The easiest way to attached code to an GameObject is to attach a MonoBehavoir script.  However, this comes with a performance penalty.  Instead, I would recommend limiting the number game objects that have attached scripts.   In fact, in many cases you can almost do away with MonoBehavoir scripts, aside from a a few "main" scripts that load the objects and gets things initialized.

For example, consider creating a custom star field that has hundreds of stars.  To create this, you could have hundreds of GameObjects with attached behavior scripts.  But this would come with quite a performance penalty. 

Instead, you could have a single behavior script that contains an array of GameObject Transforms.  This single script simply moves the transforms of each star at each frame.  This approach saves memory and saves cpu cycles.  Coupled with a nice object orientated design, you can take this same approach and extend it to most objects in your scene.


4) Look for the "new" keyword and avoid it when possible

The "new" keyword allocates a new object on the heap (or stack if a struct).  This operation is a bit expensive, and if used frequently will force frequent garbage collection.  Clearly we need to use "new" to get new objects, but avoid creating new objects within functions that are called at each frame.  If it is being called each frame, there is no reason to construct a new object each time.  Create the object once, in the start() or constructor, and then re-use it.   Some might consider this over optimization, but I consider it smart game programming.  It is a simple paradigm to follow and will drastically improve game performance.


Monday, February 25, 2013

The Advnatages of Quercus PHP

While most everyone that uses PHP uses the Zend Engine, there are a few other PHP implementations.  One such interpreter is Quercus, a PHP interpreter written in Java and runs on the JVM within a servlet container.  Here are a few reasons to give Quercus a look.


1) Performance

So, is actually Quercus faster than Zend?  In some operations it is a bit faster, and in some operations it is a bit slower.  In general, I would say that Quercus PHP has about the same performace as Zend PHP for most PHP requests.  Quercus comes in 2 flavors, interpreted mode and compiled mode.  The interpreted mode is (in my epxierence) roughly comparable to not using a code cache with Zend, while the compiled mode is comparable to using a code cache with Zend.  See the following doc for an overview of Quercus performace.

While this does not seem like much of a "win" for Quercus, it is important to point out that Quercus is not slower for a standard PHP request.   If Quercus were slower, the following points would be rather moot.  However, Querucs is fast, and combinded with the following advantages, it is a platform to be considered for PHP devleopment.


2) PHP in the front, Java in the back

Different computer languages were written for different tasks.  PHP was written as a web app language and excels at formatting data for the presentation layer.  Java is great for creating data structures, algorithms, database connectivity, transactions, etc

The great thing about Quercus is it allows us to take advantage of both languages by using them seamlessly together: with PHP as the presentation of a Java based business tier.  With Quercus, you can write your data structures and business logic with Java, which then passes the results to PHP to be formatted and sent to the client.  This process is simple because Quercus PHP can seamlessly call Java objects/methods.   Using the best parts of both languages, one can do some really cool stuff.
  • Call Lucane, Hadoop, Cassandra (and more) directly from PHP.
  • Create complex and fast data structures in Java, which are then queried and displayed with PHP.
  • Application scope objects in PHP that are backed by Java objects.
  • Utilize the rich PHP web templating, with the vast array of Java middle-ware libraries.
  • Shared data structures between PHP and Java components of an application. 
  • Choose which parts of the application are best suited for PH P and/or Java
Quercus PHP is able to do the above because, of course, Quercus is ultimately Java.  For an introduction on using Java objects with Quercus, see this.


3) Database Connection Pooling.

One of the best features of Java  is database connection pooling.  Database connection pooling allows database connections to be managed by a pool that automatically grows and shrinks according to demand.  Connection pools save resources because database connections do not need to be constantly created/destroyed which has considerable overhead, particularly when done over remote connections.  Not only does this help the web layer, it also saves resources at the database layer because only a minimal amount of persistent connections need to be maintained.

Out of the box, Quercus allows the use of database pooling without having to change a line of php/mysql code!  Moreover, one can use PHP to Java integration (see point #2) to access Java objeccts backed by JDBC connection pooling.

4)  Scalable AJAX with PHP running on Java NIO

One of the problems with most setups of PHP is that there is one (thick) process attached to each request that blocks the process/thread until the response is sent.  On the other hand, Java has the option of using NIO (non-blocking IO) in the Servlet container.  This means that there is no longer a one to one ratio between requests and threads, but there can be many thousands of requests that are being severed by a small number of threads.  This is particularly good for AJAX, because many of those connections will be waiting for the next request within a keep alive.   By simply enabling an NIO connector, Quercus can scale to handle large number of non-blocking AJAX style requests in PHP.  No reason to turn down those keep alives!


5) Scalable COMET with PHP via Servlet 3.0 Async

 NIO's best friend is the Servlet 3.0 Asynchronous processing.  Putting this two technologies together allows a highly scalable COMET style app.  Servlet 3.0 Asychronous processing allows the requst thread to immedately return to the pool and allow another thread to handle the response.  This allows a single thread to efficiently pipe messages to many listeners.  Using this technology one can create scalable push notificaitons, chat rooms, and virtual worlds.  While the above point (#4) is seamless to the PHP developer, creating COMET with PHP will require extra coding, but nothing more than calling a few Java classes (see point #2).


6) Improved Session Management.

The standard PHP implementation places all session data on the disk, which can be quite slow.  Zend PHP does allow writing sessions to a database, however this requires quite a bit of work. One thing that Zend PHP cannot do is manage the sessions directly in memory.

On ther other hand, Java Servlet containers provide several configurable session options which can be easily taken advantage of with Quercus PHP, since sessions in Quercus are written on top of Java sessions.  The following options require only a change in the xml file.  Here are some options:
  • Memory - the defualt of most servlet containers is to store the session objects in memory.  This is very fast because it does not require disk access and serialization at every request.
  • Memory to Disk - this option access the sessions from memory, but then serialized them to disk after a period of inactivity
  • Memory to Database - smilar to above but backed by a database.  This is great for distributed sessions.    
  
7) Application Scope Objects

Because the standard implemenation of PHP is share nothing,  sharing objects between processes requires a external resource: APC object cache, Memcache, or writing the object to disk.  All these approaches share a common problems.  First, the objects need to be serialized/serialized frequently.  Second, there is no garnatee that two requests are referencing the same object.  This can occur if one process retreives the object, and starts processing while another process has updated the object.

For Java Servlets, Application scope objects objects are trivial.  Because they are kept in memory, cached objects do not need to be serialized and each servlet will always have a copy of the most recent object.  Using a Java backed object in Quercus PHP, application scoped objects are simple.  Ofcourse you could always serialize the object to disk/memccahe with Quercus just like you do with standard PHP, if that is what you desire.

Another option is to use the built in Quercus APC module.  This module works just like the normal APC and it is seamless to the PHP developer.

Saturday, February 16, 2013

Java vs PHP for MySQL Peformance

Java and PHP can both be used to connect to a MySQL database.  Yet, which language/platform has faster performance with MySQL?

I ran a quick benchmark to test them out.  As always, a benchmark is simply a benchmark, you will need to look at your own situation and your own use case.

The Setup

I took a very simple database which has one table with one row, defined as the following:

      create table test_table(id int, mytext varchar(50));
      create index indexTest on test_table (id);

I populated the table with 10,000 entries. We will test 2 things.  First,  we will test how quickly we can connect to the database and retrieve one value value.  Second, we will test how long it takes to iterate over a larger result set.

Tomcat was used as the java application server, and apache2 with mod_php prefork was used for PHP.  Linux was used and the database was on the same server as the app servers.  I did not measure the time for the http request, but the only the time it took to perform the database operations.  The database was warmed up for each test.

1) Connection Speed 

In this first test I tested the connection speed, closing the connection after each iteration.  Here are the averaged results.

     Java (no connection pool)  = 6 ms to connect to MySQL
     PHP = .46 ms to connect to MySQL

PHP is the clear winner here.  Compared to PHP, Java is just embarrassingly slow at creating a fresh database connection.

While Java is  slow at creating a fresh connection every time, one rarely does this with Java.  Instead, Java typically uses connection pools.  Connection pools allow database connections to be managed by a pool and shared among requests.  This prevents having to frequently open and destroy connections.  Using the Tomcat JDBC connection pool, Java is about 4 times faster than PHP.

     Java Connection Pool = .14 ms per connect


2) Iterating over a Result Set

In this next test, we want to see how Java and PHP compare while iterating over a result set.  1000 entries were selected, with each row extracted from the result set, like in the following:

Java
      String sql = "select * from test_table where id>0 AND id <1000";
      ResultSet rs = stmt.executeQuery(sql);
      while (rs.next()) {
            String s = rs.getString("mytext");
      }

 PHP
      $sql ="select * from test_table where id>0 AND id <1000";
      $result = mysql_query($sql);
      while ($row = mysql_fetch_array($result)) {
          $s=$row["mytext"];
      }

Here are the averaged results:

    Java = 2.3 ms to iterate over 1000 entries
    PHP = 4.9 ms to iterate over 1000 entries

So, Java is almost twice as fast at this test: faster but not too much faster.


Note about Persistent Connections and Thread Pools

While I did run the above test with a Java connection pool, I did not re-run the PHP test with PHP's persistence connection.  A persistent connection would likely have matched Java's speed, however I chose not to do this because it is often not recommended to use persistent connections in PHP.   Persistent connections are often not the standard way of connecting in PHP, however connection pools are standard way of connecting in Java. (for a larger discussion on persistent connections see this and this).   So, I wanted to compare the standard approaches in each respective language.

Moreover, while persistent connections are similar to Java's connection pools, they are not the same thing.  In PHP, a persistent connection is created for the apache process and re-used for each subsequent request on that process.  In this case, each apache process would have its own persistance connection.  So, if you have 50 apache processes, then you have 50 open connections.  That connection will stay open even if that process is not even using the database.

However, with Java connection pools, the number of open connections is not dependent on the number of request threads.  Instead, the pool starts with a small number of connections and grows and shrinks according to demand.  A request thread will obtain a connection from the pool only when needed.  Thus, you often need far fewer database connections than request threads. Under low load, the pool will shrink to one maintained connection (if so configured).


 Concluding thoughts

This test demonstrates that Java is a bit faster than PHP for establishing connections and iterating over results.  So which language/platform is better for MySQL? 

If the database on the same computer as the server, I would say that both languages are about equal.  Java is faster: 4 times faster creating connections and about 2 times faster iterating over a result set.  But, that is not drastically faster and will only occupy a small fraction of the entire database call and and even smaller fraction of and entire page request.

If the database is on a different computer then the server, then you will likely want to keep the connections alive between requests to avoid the overhead of establishing a remote connection.  Here Java's connection pooling has some real advantages over PHP's persistent connections, because the thread pool allows the connection pool to grow and shrink according to demand.  However, this concept was not benchmarked in this post, so I will leave this for a future discussion. 

Friday, February 15, 2013

Java vs PHP Memory Consumption

Does PHP/Apache take less memory than Java Servlets?

Often the answer to this question is yes.  PHPis rather light on memory and resource consumption.

However, I would argue that sometimes Java uses less memory than PHP under higher loads.  It is my experience that as the number of concurrent requests increases, you will reach a time in which Java uses less memory than PHP.  This happens because PHP and Java take a different approach towards handling server requests.

*Note that this post only deals with the "standard" or "common" setup of both PHP (using apache with mod_php) and Servlets (using BIO connector).  This post is an oversimplification of a very complex topic.

The Big Fat JVM.

The JVM often thought to be (and often is) a memory hog.  The JVM can easily take 100 MB of RAM and will happily consume as much memory as you are willing to give it (this rapid consumption of allocated memory is a feature that allows the garbage collection to be run less).

However, when we  look at the JVM and the memory it consumes, we have to realize exactly what it gives us. Within that single JVM process you are running the following:
  1. App Web Server (such as tomcat).  The server runs within the JVM process and is not a separate process.   A startup Tomcat will only add a few megs to the memory heap.
  2. Code Cache:  this space holds the compilation of bytecode.  JSP/Servlets are not recompiled at every call, but held in the code cache.  For php this is often a separate module or extra install, but in Java it is built into the JVM memory space.
  3. Application Scope Objects : the ability to store large data objects.   In PHP this requires an addition module or process such as APC or memcache to store objects.
  4. Database pooling :  Database connections are not constantly created and destroyed (which creates overhead), but are shared among requests in a pool.  Shared connections often means less connections.
  5. Request Threads : In Java, the threads that handle http requests are not separate processes, but lightweight threads that run within the single JVM memory. This is most important for memory consumption.
As you can see, the JVM provides many features out of the box that would require a host of additional processes and/or modules for an equivalent PHP/Apache setup.


PHP: The little processes add up.

The last point above is really the most important, Java and PHP take a different approach to how each http request is handled.

Lets first take a look at php.  PHP forks (assuming pre-fork)  an apache process for each request.  Each apache process has its own memory space and loads all modules, the interpreter, php files, byte code, database connections, and application stack/data.   The more modules, bytcode, application memory, etc... the larger each of these processes will be.

Each process typically takes 5-30 MB, depending on how much is loaded in.  People running PHP sites often see around 20 MB per apache process (see here and here).

So, if you have 1 GB of memory allocated to these 20 MB apache processes, you can run about 50 concurrent connections.  And then you will need extra memory to run databases, APC cache, Memcache, etc.

Java: Big JVM with small request threads.

So the JVM is a big ship, but it is a ship with a lot of inertia. Lets see how a java request is handled.

When a request comes in, it is not handled by a separate process, but by a small lightweight thread.  These threads, by themselves, add almost nothing to memory, except a small (configurable) stack size and a small amount of memory added to the heap.

Unlike PHP, each thread does not need to have its own copy of files, bytcodes, compiler, runtime, databaese connections, etc, because these are all shared within the single JVM process.  Each request thread is cheap!  Thus, while it it takes quite a bit of memory to get the JVM started, each additional concurrent connection requires far less memory.

So, assuming that you had 1GB allocated for tomcat and each request thread takes about 3MB ( assuming about 1MB thread overhead  with 2 MB application data) and that the JVM aside takes around 100 MB. In this situation, you can run about 300 concurrent connections.   You can play with you own numbers to get your own estimated number of concurrent connections.


Who really cares, request times are so short, so we don't need many concurrent connections.

But the point is that it does matter.  Even if your requests are short, keep-alives will persist your connections.  A keep-alive will keep the entire process/thread until the timeout.  So if you have a keep alive of 10 second with 50 users are clicking around fairly often, then you will have 50 processes/threads alive at all times.  For small threads, this is not a big deal.  For bigger processes, this is a big deal.

You can alleviate this by removing or drastically reducing keep-alives, but this really only becomes a problem because of process size.  If one were using a thread model, one would not have to cut the keep-alive to a ridiculously small time -  which is particularly important for high response time for ajax style apps.

Give it a test.

Spin up a small VPS.  Create equivalent tests in php and java. Slam it with a testing program with keep-alives.  See which one starts thrashing the swap first.

Concluding thoughts.

This might have sounded like a knock against PHP, which it is not.  It is simply pointing out the differences between how the two web app platforms work.   Often php will require much less resources for smaller load applications.  And PHP can clearly scale (horizontally and vertically) to accomplish most any web app necessary.

However, it is my experience that as the number of concurrent requests increases, you will reach a time that Java will use less memory than PHP/apache.   Moreover, this fact is not the only (nor the primary) factor when choosing a language for a project, just something to think about.

Thursday, February 14, 2013

Pointers to Functions in Java


It is often thought that the Java language does not have pointers to methods.  In some sense it is true, but the feature is kind of there – it is just a little trickier to use than other languages.
Java method pointers comes via reflection and the ability to have a reference to a method. Given a particular class, one can grab a reference to methods of that class. These methods can then be passed around and invoked - as one would expect with pointers to methods.

Let's see how this works, say we had a class Person defined as such and we want to pass around specific methods of this class.

public class Person {
    String firstName, lastName;
    int age;
    public Person(String f, String l) {
        firstName=f;
        lastName=l;
    }
    public String getFullName() {
        return firstName + " " +lastName;
    }
     public void setAge(int age ) {
         this.age=age;
    }
}



Getting a method from a class:

Using reflection we can obtain a method of a class by calling the getMethod() of a class, which can then be invoked  For example:

[1]    Person p = new Person("Geroge", "Washington");
[2]    Method method = Person.class.getMethod("getFullName");
[3]    String s  = (String) method.invoke(p);
[4]    System.out.println(s);

Lets break down the code.  Line one creates the an instance of the object.  Line 2 gets a reference to a method of the class person.  This is how we get a reference to a method!!  Line 3 invokes that method on a particular object (p), and finally we print out the results 


Handling Method Parameters and Arguments

The above method had no parameters.  Things get a bit more complex when we have to deal with method parameters.

Method method = Person.class.getMethod("setAge", int.class);
method.invoke(p, 33);

If the method has parameters, we need to tell Java "which" method we want, as there can be multiple methods with the same name but different parameters.  We let Java know which parameter in getMethod by supplying an array (or sequence) of "Class" types.  In this case, the method setAge takes an int, so we supply the class of int, which can be obtained by through int.class.  If it took a String we would use String.class

What if there were two arguments to that method?  Imagine there was a changeName method to class Person that took a new first and last name, we would obtain that method with the following call:

method = Person.class.getMethod("changeName", String.class, String.class);
method.invoke(p, "Thomas", "Jefferson");


Where to go from here?

Once you know how to grab a method of a class/object, you can do lots of interesting stuff.  You can pass method reference around between methods, you can store the methods in data structures to be invoked at another time, etc.

But in order to be effective at using method references in Java, you need to have a solid grasp of Reflection in Java.  And you will likely want to wrap the method references in a layer of abstraction, as the reflection classes are a bit cumbersome.

Check out some of the core docs:

- the Class docs 
- the Method docs