Pencarian

Rss Posts

 

 

 

Berita pada kategori ‘Pemrograman’

The Mysterious Phantom Reference

Sep 29, 2011

I talk about java.lang.ref.* in my performance tuning course because these things (along with anything that implements finalize) are more expensive to create than normal objects and require at least two rounds of GC before you’re completely rid of them. Of the bunch, that includes Reference, WeakReference, SoftReference and two other private reference classes that get mixed up with finalization, PhantomReference has to be the strangest.

 

Though I talk about PhantomReference, I’ve never used to nor could I even think of a situation where I’d even think to use it! Which is, I guess, why I’ve never used it. In fact, I can’t remember ever seeing them used any where in the wild. But, as is the case with just about everything,  if you talk to enough people you will eventually run into someone that has tried to used even the most arcane features in Java. True to this point, this week, I finally ran into someone that had a convincing use case for PhantomReference.

 

This person was trying to track down who was leaking JDBC connections. His idea was to wrap the connection in a PhantomReference and when the connection was discarded (and not closed), the garbage collector would put the object into a supplied ReferenceQueue, you’d grab the object from the ReferenceQueue and not only close it, you’d try to sort out who should have closed it. As with just about everything, the devil is in the details and in this case the details are; reference queue doesn’t return the object wrapped in the PhantomReference, it returns the PhantomReference and PhantomReference.get() always returns null. The reason for this is that the wrapped object is half collected and should not be reconnected to anything. I get that but what I don’t get it given this condition, why is PhantomReference marketed as alternative mechanisum to finalization. WIth no means to access the wrapped object, (reflection aside) there isn’t much one can do to clean things up. Consider the following code.

 

public class Foo {

 

    private String bar;

 

    public Foo(String bar) {

        this.bar = bar;

    }

 

    public String foo() {

        return bar;

    }

}

 

So lets say after the object has been completely dereferenced by the application I want to some how call foo(). Here is some code that I expected to work that would do this with one niggle.

 

        

 

// initialize

ReferenceQueue<Foo> queue = new ReferenceQueue<Foo>();

ArrayList< PhantomReference<Foo>> list=new ArrayList<PhantomReference<Foo>>();

 

for ( int i = 0; i < 10; i++) {

    Foo o = new Foo( Integer.toOctalString( i));

    list.add(new PhantomReference<Foo>(o, queue));

}

 

// make sure the garbage collector does it’s magic

System.gc();

 

// lets see what we’ve got

Reference<? extends Foo> referenceFromQueue;

for ( PhantomReference<Foo> reference : list)

    System.out.println(reference.isEnqueued());

 

while ( (referenceFromQueue = queue.poll()) != null) {

    System.out.println(referenceFromQueue.get());

    referenceFromQueue.clear();

}

 

PhantomReference takes an instance of Foo and a ReferenceQueue. Since no handles are kept to Foo, it should immediately be dead. Next, tell the VM to collect as there isn’t enough in heap for it to trigger a collection naturally. The first thing I’m going to ask the PhantomReference is; have you been enqueued. In this case the answer will be true. Next I ask the queue for the reference but as you can see, calling get() always returns null.

 

About the only solution that made sense is to wrap the resources or objects you wanted to interact with in a subclass of PhantomReference.

 

public class FinalizeStuff<Foo> extends PhantomReference<Foo> {

 

    public FinalizeStuff(Foo foo, ReferenceQueue<? super Foo> queue) {

        super(foo, queue);

    }

 

    public void bar() {

        System.out.println("foobar is finalizing resources");

    }

}

 

In this case I’m not going to wrap Foo in the subclass as that would seem to violate the spirit of PhantomReference. Instead I’m going to wrap resources associated with Foo and interact with them. Now I can do this.

 

// initialize

ReferenceQueue<Foo> queue = new ReferenceQueue<Foo>();

ArrayList< FinalizeStuff<Foo>> list = new ArrayList<FinalizeStuff<Foo>>();

ArrayList<Foo> foobar = new ArrayList<Foo>();

 

for ( int i = 0; i < 10; i++) {

    Foo o = new Foo( Integer.toOctalString( i));

    foobar.add(o);

    list.add(new FinalizeStuff<Foo>(o, queue));

}

 

// release all references to Foo and make sure the garbage collector does it’s magic

foobar = null;

System.gc();

 

// should be enqueued

Reference<? extends Foo> referenceFromQueue;

for ( PhantomReference<Foo> reference : list) {

    System.out.println(reference.isEnqueued());

}

 

// now we can call bar to do what ever it is we need done

while ( (referenceFromQueue = queue.poll()) != null) {

    ((FinalizeStuff)referenceFromQueue).bar();

    referenceFromQueue.clear();

}

 

This works though in some variations of this implementation main thread was racing against another thread (GC is my best guess). Note the strange need to cast. I could not sort out how to avoid it so if someone wants to comment….. Returning to the use case, the subclass that was created for the JDBC leak captured a stacktrace which was logged when the PhantomReference was pulled from the reference queue.

 

I’m happy for comments from anyone that has actually found a good use for PhantomReference as quite frankly, I still don’t understand why anyone would use it in leu of finalization. While finalization isn’t perfect, it’s not the dog that everyone makes it out to be and it’s far safer to use than PhantomReference is. For example, if anything bad happens during finalization, you’ll only shoot down a helper thread. Furthermore, the only way finalize will not be called is if the VM fails catastrophically or you’ve requested a shutdown but have failed to specify that finalizers (RunTime.runFinalizersOnExit()) should run before doing so. No such guarantees exist for PhantomReference.

 

PS, One point in favor of PhantomReference over finalize is that you could configure your system to optionally wrap objects. But then, you could use an interface with two implementations, one that implemented finalize() and one that doesn’t to achieve the same effect. So, I’m still scratching my head over this one.

JavaScript: Asynchronous Script Loading and Lazy Loading – Federico Cargnelutti

Jul 12, 2011

Most of the time remote scripts are included at the end of an html document, right before the closing body tag. This is because browsers are single threaded and when they encounter a script tag, they halt any other processes until they download and parse the script. By including scripts at the end, you allow the browser to download and render all page elements, style sheets and images without any unnecessary delay. Also, if the browser renders the page before executing any script, you know that all page elements are already available to retrieve.

However, websites like Facebook for example, use a more advanced technique. They include scripts dynamically via DOM methods. This technique, which I?ll briefly explain here, is known as ?Asynchronous Script Loading?.

Lets take a look at the script that Facebook uses to download its JS library:

(function () {
    var e = document.createElement('script');
    e.src = 'http://connect.facebook.net/en_US/all.js';
    e.async = true;
    document.getElementById('fb-root').appendChild(e);
}());

When you dynamically append a script to a page, the browser does not halt other processes, so it continues rendering page elements and downloading resources. The best place to put this code is right after the opening body tag. This allows Facebook initialization to happen in parallel with the initialization on the rest of the page.

Facebook also makes non-blocking loading of the script easy to use by providing the fbAsyncInit hook. If this global function is defined, it will be executed when the library is loaded.

window.fbAsyncInit = function () {
    FB.init({
        appId: 'YOUR APP ID',
        status: true,
        cookie: true,
        xfbml: true
    });
};

Once the library has loaded, Facebook checks the value of window.fbAsyncInit.hasRun and if it?s false it makes a call to the fbAsyncInit function:

if (window.fbAsyncInit && !window.fbAsyncInit.hasRun) {
    window.fbAsyncInit.hasRun = true;
    fbAsyncInit();
}

Now, what if you want to load multiple files asynchronously, or you need to include a small amount of code at page load and then download other scripts only when needed? Loading scripts on demand is called ?Lazy Loading?. There are many libraries that exist specifically for this purpose, however, you only need a few lines of JavaScript to do this.

Here is an example:

$L = function (c, d) {
    for (var b = c.length, e = b, f = function () {
            if (!(this.readyState
            		&& this.readyState !== "complete"
            		&& this.readyState !== "loaded")) {
                this.onload = this.onreadystatechange = null;
                --e || d()
            }
        }, g = document.getElementsByTagName("head")[0], i = function (h) {
            var a = document.createElement("script");
            a.async = true;
            a.src = h;
            a.onload = a.onreadystatechange = f;
            g.appendChild(a)
        }; b;) i(c[--b])
};

The best place to put this code is inside the head tag. You can then use the $L function to asynchronously load your scripts on demand. $L takes two arguments: an array (c) and a callback function (d).

var scripts = [];
scripts[0] = 'http://www.google-analytics.com/ga.js';
scripts[1] = 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js';

$L(scripts, function () {
    console.log("ga and jquery scripts loaded");
});

$L(['http://connect.facebook.net/en_US/all.js'], function () {
    console.log("facebook script loaded");
    window.fbAsyncInit.hasRun = true;
    FB.init({
        appId: 'YOUR APP ID',
        status: true,
        cookie: true,
        xfbml: true
    });
});

You can see this script in action here (right click -> view page source).


Filed under: Design Patterns, Programming, Software Architecture the original (another 826 bytes)

PHP Returning Numeric Values in JSON – Lorna Mitchell

Jul 12, 2011


When I wrote about launching a prototype of a new
joind.in API, quite a few people started to try it out. My friend David Soria Parra emailed me to point out that many of the numbers in the API were being returned as strings. He said:

It’s just a standard problem of PHP REST services. When I try to access it with java I have to convert it over and over again to ints.

I did have a quick look at the PHP manual page for json_encode but I didn’t see anything mentioning this. A few weeks later (my inbox is a black hole and it takes a while to process these things) I fell over a throwaway comment to an undocumented constant JSON_NUMERIC_CHECK, and I added the constant name to my todo list. In the time it took for me to actually get around to googling for this, some wonderful person updated the PHP manual page (this is why I love PHP) to include it as a documented option, and someone else had added a user contributed note about using it.

It turns out, this constant does exactly what I need. Here’s a simple use case:

echo json_encode(array(‘event_id’ => ‘603′));
echo json_encode(array(‘event_id’ => ‘603′), JSON_NUMERIC_CHECK);
?

and the output:

{"event_id":"603"}
{"event_id":603}

There are probably some situations in which you don’t want all your looks-like-a-number data to be returned as a number, but for now it seems to be a good fit for api.joind.in.

PHP color scheme – Henrik Sarvell

Jul 09, 2011

Copyright ? 2011 http://www.prodevtips.com. Visit the original article at http://www.prodevtips.com/2011/07/09/zenburn-for-geany-php-color-scheme/.

Color theming in Geany is quite a no-brainer if you know how to go about it…. Read More

EclipseLive: Upcoming Event: Reminder – C/C++ Development Tooling for Eclipse Indigo

Apr 19, 2011

Event Date: April 21, 2011 4:00 pm GMT-8

Register Now

Doug Schaefer (Wind River)
?
Abstract:

The CDT Project provides professional strength tools for C/C++ developers. Doug Schaefer, lead of the Eclipse CDT project, will present an overview of the CDT and demo the latest work for the Indigo release, coming at the end of June. Topics will include support for Android native development, refactoring, CODAN static analsis, Visual C++ integration, support for desktop and embedded development and what’s next for the project.

Total running time will be approximately 1 hour

9:00 am PST / 12:00 pm EST / 4:00 pm UTC / 6:00 pm CET – Convert to other time zones

Thanks to Adobe for contributing their Adobe Acrobat Connect product to host this webinar.


delicious delicious | digg digg | dzone dzone

Improved URL auto-linking in Horde – Chuck Hagenbuch

Mar 13, 2011

Horde now uses John Gruber’s regex pattern for matching URLs in text (http://daringfireball.net/2010/07/improved_regex_for_matching_urls).

Quick introduction to Embeddability of GlassFish Open Source Edition 3.1

Mar 02, 2011

Embeddability of GlassFish is been around for quite some time now. In 3.1, the embeddable APIs have been revised. Most of the GlassFish community is already aware of the API revision, however I would like to briefly describe the revised APIs in this blog and welcome any feedback.

Embeddable API overview:

API JavaDocs are at http://embedded-glassfish.java.net/nonav/apidocs/

The APIs are briefly categorized as :

(a) Top level APIs (org.glassfish.embeddable) : Provides classes and interfaces necessary to embed GlassFish and perform lifecycle operations, application deployments and runtime configurations

(b) Scattered Archive APIs (org.glassfish.embeddable.archive) : Abstraction for a scattered Java EE archive (parts disseminated in various directories).

(c) Web Container APIs  (org.glassfish.embebdable.web, org.glassfish.embeddable.web.config) : Provides classes and interfaces necessary to programmatically configure embedded WebContainer and create contexts, virtual servers, and web listeners.

(d) Advanced pluggability (org.glassfish.embeddable.spi) : Provides classes and interfaces necessary to plugin a custom GlassFish runtime.

(e) EJB container APIs (javax.ejb.embeddable) : Refer "Embedded Server Guide" for EJB embeddable APIs

Basic examples of embedding GlassFish and deploying applications to embedded GlassFish:

These examples are can be run with either of the following jars in your CLASSPATH:

Full profile uber jar : http://download.java.net/maven/glassfish/org/glassfish/extras/glassfish-embedded-all/3.1/glassfish-embedded-all-3.1.jar
Web profile uber jar: http://download.java.net/maven/glassfish/org/glassfish/extras/glassfish-embedded-web/3.1/glassfish-embedded-web-3.1.jar
Installed GlassFish’s shell jar : $GF_INSTALLATION/lib/embedded/glassfish-embedded-static-shell.jar

Once you have ANY ONE of the above jar file with you, GlassFish can be embedded in your application by simply doing:

import org.glassfish.embeddable.*;

/** Create and start GlassFish */
GlassFish glassfish = GlassFishRuntime.bootstrap().newGlassFish();glassfish.start();

Let us say that you would like 8080 web container port to be started while embedding GlassFish, then you have to do this:

import org.glassfish.embeddable.*;

/** Create and start GlassFish which listens at 8080 http port */
GlassFishProperties gfProps = new GlassFishProperties();
gfProps.setPort("http-listener", 8080); // refer JavaDocs for the details of this API.

GlassFish glassfish = GlassFishRuntime.bootstrap().newGlassFish(gfProps);glassfish.start();

Or let us say that you have 3.1 installation and want to embed GlassFish domain1 in your application, then you can do:

import org.glassfish.embeddable.*;

/** Bootstrap the GlassFish runtime pointing to 3.1 installation */BootstrapProperties bsProps = new BootstrapProperties();bsProps.setInstallRoot(System.getEnv("GF_INSTALLATION"));GlassFishRuntime gfRuntime = GlassFishRuntime.bootstrap(bsProps);

/** Point GlassFish to domain1 */
GlassFishProperties gfProps = new GlassFishProperties();
gfProps.setInstanceRoot(System.getEnv("GF_INSTALLATION") + "/domains/domain1");
GlassFish glassfish = gfRuntime.newGlassFish(gfProps);

glassfish.start();

Note: If you have a custom domain.xml while embedding GlassFish, then you can use setConfigFileURI(String configFile) API of GlassFishProperties. JavaDoc has all the details.

Once you have the GlassFish embedded and is running, you may like to deploy a pre-built Java EE archive using the code below:

import org.glassfish.embeddable.*;

// Obtain the deployer from the glassfish which is embedded via the piece of code above.Deployer deployer = glassfish.getDeployer();

// syntax of deployment params are same as how they are passed to 'asadmin deploy' command.deployer.deploy(new File("simple.war"), "--contextroot=test", "--name=test", "--force=true");

// if you have no deployment params to pass, then simply do this:deployer.deploy(new File("simple.war")); 

If your archive is not pre-built, instead it’s components are scattered in multiple directories, then you may be interested in using the scattered archive APIs:

import org.glassfish.embeddable.*;import org.glassfish.embeddable.archive.*;

Deployer deployer = glassfish.getDeployer();

// Create a scattered web application.ScatteredArchive archive = new ScatteredArchive("testapp", ScatteredArchive.Type.WAR);// target/classes directory contains my complied servletsarchive.addClassPath(new File("target", "classes"));// resources/sun-web.xml is my WEB-INF/sun-web.xmlarchive.addMetadata(new File("resources", "sun-web.xml"));// resources/MyLogFactory is my META-INF/services/org.apache.commons.logging.LogFactoryarchive.addMetadata(new File("resources", "MyLogFactory"), "META-INF/services/org.apache.commons.logging.LogFactory");

deployer.deploy(archive.toURI())

Similarly, the scattered enterprise application (EAR type) can be deployed like this:

import org.glassfish.embeddable.*;import org.glassfish.embeddable.archive.*;

Deployer deployer = glassfish.getDeployer();

// Create a scattered web application.ScatteredArchive webmodule = new ScatteredArchive("testweb", ScatteredArchive.Type.WAR);// target/classes directory contains my complied servletswebmodule.addClassPath(new File("target", "classes"));// resources/sun-web.xml is my WEB-INF/sun-web.xmlwebmodule.addMetadata(new File("resources", "sun-web.xml"));

// Create a scattered enterprise archive.ScatteredEnterpriseArchive archive = new ScatteredEnterpriseArchive("testapp");// src/application.xml is my META-INF/application.xmlarchive.addMetadata(new File("src", "application.xml"));// Add scattered web module to the scattered enterprise archive.// src/application.xml references Web module as "scattered.war". Hence specify the name while adding the archive.archive.addArchive(webmodule.toURI(), "scattered.war");// lib/mylibrary.jar is a library JAR file.archive.addArchive(new File("lib", "mylibrary.jar"));// target/ejbclasses contain my compiled EJB module.// src/application.xml references EJB module as "ejb.jar". Hence specify the name while adding the archive.archive.addArchive(new File("target", "ejbclasses"), "ejb.jar");

deployer.deploy(archive.toURI())

Finally, towards the end of your application, you would like to stop/dispose your embedded GlassFish:

import org.glassfish.embeddable.*;

/** Stop GlassFish */
glassfish.stop(); // you can start it again.

/** Dispose GlassFish */glassfish.dispose(); // you can not start it again. But you can embed a fresh glassfish with GlassFishRuntime.bootstrap().newGlassFish()

More Examples:

If you checkout https://svn.java.net/svn/glassfish~svn/trunk/v3/tests/embedded you will find many more examples which cover embeddable web container APIs also.

Feedback:

If you have any feebback on the APIs, please send them to dev@glassfish.java.net or dev@embedded-glassfish.java.net

Using Horde_Xml_Element to quickly generate XML from arrays – Chuck Hagenbuch

Feb 20, 2011

Horde_Xml_Element gives you a quick shortcut for taking PHP arrays and turning them into XML.

Symfony ? subfolders for partials – Anna Filina

Feb 19, 2011

Symfony 1.2 ? 1.4 expects all partials to follow this convention: templates/_partial.php

What happens when you need to organize your partials in subfolder? I tried a number of ?Symfunky? avenues. Feel free to skip to the solution.

Avenues Explored

I first try the call the include_partial helper with ?subfolder/partial?, but that results in Symfony attempting to find the partial in the ?subfolder? module.

Alright, so I try ?module/subfolder/partial?, but that results in Symfony looking for ?_subfolder/partial? because it simply split at the first backslash. I don?t blame the framework developers: I am trying to do something it was not meant to do.

So now I realize that we can set any template from an action using $this->setTemplate(?subfolder/_partial?). Since actions are NOT partials by definition, I decide to use a component. Unfortunately the component doesn?t allow the developer to override templates.

I am starting to feel that the framework mocks me.?So this is how you wanna play it, huh? I will override your sfView class, load it in factories.yml, and there?s nothing you can do about it (insert diabolical laughter)! But then, after almost half an hour, I realize that I?m trying to make it too elegant for something so basic as concatenating a few strings.

Solution

The solution ended up ridiculously simple and does not risk breaking any existing code.

1. Copy get_partial() helper with an extra param: get_partial_subfolder($templateName, $vars = array(), $subfolder)
2. Edit the line that concatenates the file name: $actionName = $subfolder.?/_?.$templateName; (instead of ?_?.$templateName)

There you go, no more headaches. Just remember to use ?echo get_partial()? instead of ?include_partial()? unless you want to override that helper as well. If you are unsure how to create custom helpers, see here under Adding Your Own Helpers: http://www.symfony-project.org/book/1_2/07-Inside-the-View-Layer

PHP on Azure and you in Vegas – Michelangelo van Dam

Feb 19, 2011

If you’re developing apps in PHP and you want a challenge that will get you some places, be sure to check out the PHP on Azure contest. Build an app with PHP, deploy it to Windows Azure and participate in a contest with a killer prize: an all-in trip to Las Vegas!

The rules are simple:

  • your app has to be written in PHP
  • preferably own development app
  • use as much as Windows Azure services
  • blog about overcoming this challenge (good/bad/ugly)

A jury will review your app and give you points on implementation, challenge and usage of Windows Azure technologies. But also on how you documented the process of deploying your app to Windows Azure.

Register before February 28, 2011. The contest itself runs from February 1, 2011 until May 15, 2011. If you register quickly, you can get attend a free Windows Azure training course given by Maarten “Mr. Azure” Balliauw on February 22, 2011.

Show the world your skills and participate. Full details of the contest can be found on http://phpazurecontest.com.

If you’re unsure how to start, I’m working on an example application to be deployed anywhere, including Windows Azure.