One more reason to use Servlet 3 (Java) on the serverside instead of PHP

April 20, 2011

After reading an excellent article on Asynchronous processing support in Servlet 3.0 at JavaWorld.com, I have one more reason to use Servlet 3 providers. Just as Jetty Asynchronous REST example shown, real world requets that aggregates several backend call responses benefit from the asynchronous nature by freeing valuable CPU resources, improving server scalability.

Try this with PHP ;)

Kudos for the JSR expert group for making this a standard!

PHP singleton scope is request scoped

May 26, 2010

In my current job I’m working with some PHP codes for which I’ve implemented the singleton pattern. My testcase is quite straightforward and consists of a singleton that stores the time at which it was instantiated:

class MySingleton {
    private static $myVar;

    private static $instance;

    private function MySingleton() {
        self::$myVar = time();
    }

    public static function getInstance() {
        if (! isset(self::$instance)) {
            self::$instance = new MySingleton();
        }

        return self::$instance;
    }

    public function getMyVar() {
        return self::$myVar;
    }
}

echo "Time: " . MySingleton::getInstance()->getMyVar();

Now, let’s test it. This is the result for the first invocation:

Time: 1274882765

and now a second invocation:

Time: 1274882775

So what’s going on here? PHP architecture is designed to fork a new process on every page request. That means that the singleton only lasts for a request. On the next request, it is instantiated again, that’s why we get different timestamps. What if we want for the singleton to span several requests, i.e. a session? Here is a modified version:

class MySingleton {
    private static $myVar;

    private static $instance;

    private function MySingleton() {
        self::$myVar = time();
    }

    public static function getInstance() {
        if (! isset(self::$instance)) {
            self::$instance = new MySingleton();
        }

        return self::$instance;
    }

    public function getMyVar() {
        return self::$myVar;
    }
}

session_start();

if (! isset($_SESSION["mySingleton"])) {
    $_SESSION["mySingleton"] = MySingleton::getInstance()->getMyVar();
}

echo "Time: " . $_SESSION["mySingleton"];

The result is weird:

Time:

There’s no output because I used “static” scope for $myVar in MySingleton and PHP won’t serialize it. So I must remove the “static” keyword to make it an instance variable:

myVar = time();
    }

    public static function getInstance() {
        if (! isset(self::$instance)) {
            self::$instance = new MySingleton();
        }

        return self::$instance;
    }

    public function getMyVar() {
        return $this->myVar;
    }
}

session_start();

if (! isset($_SESSION["mySingleton"])) {
    $_SESSION["mySingleton"] = MySingleton::getInstance();
}

echo "Time: " . $_SESSION["mySingleton"]->getMyVar();

and now it works wonderfully thru all invocations… well, at least for the same session. If there are multiple sessions, each of them will have their own singleton so at any point in time, there will be N “singletons” given N clients.

In conclusion
PHP singletons are request scoped, or at most session scoped. However, it might not worth the effort to span its scope to session since PHP has to serialize sessions to disk, memcached, or whatever mechanism used for session serialization, and it might lead to an I/O problem. You should weight the cost of instantiation of objects and session serialization. In general, I would recommend session variables as an exception. Try to externalize states by embedding them to the URL (such as the current page in a paginated request) and reserve session variables for simple variables such as page hits counter in a session fashion.

Get active thread count on JMeter

April 20, 2010

While integrating swirstatdsample from sourceforge.net to retrieve remote host system stats I bumped into an interesting problem which is that rstatd sampler will run forever until we shut it down. So, this make it unsuitable for continuous builders like Hudson that run Performance Plugin to obtain JMeter performance trends. To work around this, I needed to stop the test when JMeter active thread count is equal to 1, i.e. only the rstat monitor should be running. After searching for almost a day I found this from JMeter user manual seccion 19.5.7 “__javaScript”:

Rhinoscript allows access to static methods via its Packages object. See the Scripting Java documentation. For example one can access the JMeterContextService static methods thus: Packages.org.apache.jmeter.threads.JMeterContextService.getTotalThreads()

Thus in JMeter the total threads active at any given time is available at JMeterContextService. You can either use the __javaScript function as explained above or use BeanShell Sampler which allows a more Jav-like syntax:

activeThreadCount = org.apache.jmeter.threads.JMeterContextService.getTotalThreads();

Install RSTATD on Ubuntu 9

April 20, 2010

Today I had the pleasure (or pressure) to install RSTATD on Ubuntu since we needed to monitor one of our hosts during a stress test. It turned out to be not so simple so I’m documenting the steps here:

  1. Install the packages:

    sudo xinetd rstatd

    We need to specifically ask for xinetd since we need to configure RSTATD service below.

  2. Create the file “/etc/xinetd.d/rstatd” with the following content

    # default: off
    # # description: An xinetd internal service which rstatd’s characters back to clients.
    #
    service rstatd
    {
    type            = RPC
    rpc_version     = 2-4
    socket_type     = dgram

    protocol        = udp
    wait            = yes
    user            = root
    log_on_success  += USERID

    log_on_failure  += USERID
    server          = /usr/sbin/rpc.rstatd
    disable         = no
    }

  3. Install rstat-client (optional):

    sudo apt-get install rstat-client

  4. To test it (using rsysinfo from rstat-client package):
    root@ci-server3:~# rsysinfo localhost
    System Information for: localhost
    uptime:  24 days, 17:32, load average: 0.05 0.07 0.07
    cpu usage (jiffies): user 1455679  nice 550  system 624328  idle 420845047
    page in: 2308807  page out: 16027072   swap in: 673  swap out: 4985
    intr: 158243781     context switches: 346475642
    disks: 1383151 0 0 0
    ethernet:  rx: 1901663   rx-err: 58
    tx: 1271589   tx-err: 0    collisions: 0
  5. That’s it!

Mounting Samba drive in Ubuntu 9.10 without symbolic links

February 20, 2010

Today I was trying to access a Samba file server in my network when I run into the issue that a symbolic link is retrieved “as is” from the Samba server instead of following it. It puzzled me at first since I thought that this was a server configuration but it turns out that the client can decide on it as well.

smbmount //server/share /mntpoint -o username=user password=pass nounix

Note the nounix option which does the trick to follow symbolic links.

And if you need this drive to be mounted upon start you can add an entry in /etc/fstab:

//sambaserver/clee   /mnt/sambaserver/clee  cifs  credentials=/root/.smbcredentials,dir_mode=0777,file_mode=0777,nounix   0  0

Where /root/.smbcredentials contains your user and password in this format:

username=your_username
password=your_password

Remember to change the permissions also:

sudo chmod 600 /root/.smbcredentials

Sources:

http://brainwreckedtech.wordpress.com/2009/11/29/fixit-linux-client-cant-follow-symlinks-on-a-samba-server/

http://www.guia-ubuntu.org/index.php?title=Montar_comparticiones_remotas_usando_smbfs_y_cifs

Setting up Hudson for your Maven 2 project hosted on GoogleCode – step by step

December 12, 2009

You started your GoogleCode project but don’t know how to set your project up with Hudson? If so, read on.

Step one: get authenticated with SVN repository

First you should be aware that SVN client caches your credentials. So in the machine where Hudson runs, log in as the user that runs Hudson and issue a SVN command against your repository as instructed here:

http://blogs.open.collab.net/svn/2009/07/subversion-16-security-improvements.html

Step two: set up Hudson plugin for GoogleCode

To install the plugin go to to Hudson Dashboard -> Manage Hudson -> Manage Plugins. Under the Available tab, find the GoogleCode plugin and click on install.

Step three: set up your project

Go to Hudson Dashboard -> New Job. Enter the project name and click on “Build a maven2 project”. Click on ok. Enter the Google code website which should be:

http://code.google.com/p/<project name>/

For the source management section, please note that there is a bug in GoogleCode plugin that will fail to authenticate the developer connection with GoogleCode so please follow the workaround here to complete your setup:

http://malsserver.blogspot.com/2009/04/hudson-maven-release-plug-in-plug-in.html

And that’s it! Happy coding!

Perforce BEST & WORSE practices

October 8, 2009

All regular work should be done in trunk, rather than branches

The reason to do this is that all changes to trunk should be traceable from day zero and by branching we lose the revision history. The purpose of a branch is generally to create a release and apply patches to it, thus it makes sense to isolate the revision history from the trunk since we already know the changelist at which we branched from trunk. The same concept applies to development branches.

If big changes are to be made on branches involving file locations change, create a branch spec

Certain kinds of changes like maven-ization require moving files around to comply with the Maven convention though it’s best to override the convention by specifying multiple resource directories and at a later time divide them into multiple modules to conform a Maven multi-module project. But in case you must move them because of other reasons (e.g. you mistyped the name), create a branch spec that maps the original location of the moved elements to the new location so that you can integrate changes from the trunk until you finish your work in your branch. Note that SVN won’t detect which revisions have already been integrated unlike Perforce, so you are URGED to put the integrated revisions in your commit message to keep track of integrated revisions.

Maven scope tips and tricks

September 8, 2009

I think most of us are aware of the benefit of making an Eclipse project A depend on another project B directly, instead of depending on the project B jar. Just in case you don’t, consider the scenario where project A is a WAR application and B is a JAR containing your domain objects. Then you deployed it using WTP server support or Sysdeo Tomcat plugin to test it locally. The difference is the following:

  • Using a JAR of project B means that if you happen to modify any class in B, then the JAR is inconsistent and you will need to restart the context to see the changes.
  • On the other hand, if you depend on project B, then you can take advantage of the JVM’s code HotSwap and see your changes right away, without restarting the web application context.

In order to make your multi-module maven project declare dependencies between the modules of the project, you should use <scope>compile</scope> and not any other combination (such as “provided” as I’ve seen in some production code). This way, Eclipse will recognize the dependency as a Eclipse project and won’t include it as a JAR

Live Messenger not notifying new mails / updating read mail count

June 15, 2009

Somewhere in the time, I’ve updated to a newer Live Messenger and stopped receiving new mail notificacions (the familiar popup windows saying “You’ve received a new mail from XYZ”). I’ve checked the option to notify me of new mails in Tools -> Settings without luck:

mail-alert-checked

The "Display alerts when e-mail is received" option is checked

What’s more, the new mail count does not update after messages are read as it used to behave. Now, you have to sign out of Live Messenger and log back in again to have them refreshed. I talked to a bunch of friends running Live Messenger and the problem seems to be widespread; there are people running Live Messenger 2008, 2009 and a lot of them where having problems.

The new mail count does not update at all after mails being read

The new mail count does not update at all after mails being read

Having that said, I decided to report a bug to Microsoft but Google is not telling me the place where I could report it. So, I’m posting here until someone points me to the right URL.

Blogger vs. WordPress (part 2)

June 3, 2008

Well, while writing another post I found out another missing feature for Blogger. It seems that I’m not giving Blogger a break after all ;)

Have you ever tried to add an internal link to your post? Consider a really long post:

This is a loooooong post which links to paragrah 3 in this post.

Paragraph 1…..

Paragraph 2…..

Paragraph 3 !!!

Try to do the same in Blogger

WordPress 7 – Blogger 1


Follow

Get every new post delivered to your Inbox.