Friday, March 16, 2012

What is AtomicReference for really?

we had a discussion about AtomicReference at work the other day, it appears that none of us really understand why we should use AtomicReference based on a quick glimpse at the java doc provided.

The confusion comes from that we all firmly believe reference assignment is atomic in java, so why both with AtomicReference.

I decided to do some research on it and found this great post: Memory Barriers. It looks like there are several benefits of using AtomicReference.

Internally AtomicReference marks the value volatile, which creates a memory barrier that a, makes sure no thread is reading out dated data, b, provides happens-before guarantee because your code won't be reordered by compiler. If you only use the get/set method of AtomicReference, you are essentially marking your variable volatile in a fancy way.

The other interesting method is compareAndSet(expected, newVal). With care, AtomicReference can be used as an efficient way to do synchronization, especially when concurrent change happens rarely. to do this, the thread calls compareAndSet instead of set. If it fails, then it means that the value had been updated, so this thread has to deal with the conflict, such as abandon its change, overwrite, or merge.

In summary, AtomicReference differs from other atomic types in the concurrency package that it doesn't offer the typically desired atomic action like getAndIncrement, but they are similar that they all provide compareAndSet methods.

Tuesday, April 26, 2011

content assist issue in Flash Builder eclipse plugin

I had some rough time trying to get standalone flash builder version 4 to work with Java code and Tomcat. After hours of scratching my head, I gave up. It just shouldn't be this hard. But if you are adventurous enough to give it a try, here is a great tutorial you may want to read first: http://flashworks.wordpress.com/2011/03/25/java-flex-blazeds-project-solving-issues-with-flash-builder-4-stand-alone/

So my next logical step is to install flash builder plugin to an eclipse installation. I know eclipse pretty well so the java/maven/wtp/tomcat parts went smooth without any drama. Flash builder plugin installed fine. And I was able to import flex projects and tweak the class path to make it build. The only thing missing in this setup is content assist, where I don't get code complete, API suggestions, or open declaration (F3) etc.

After two days of suffering without content assist and numerous googling, I finally found this great discussion which gave me a pointer to get it fixed. :)
http://forums.adobe.com/thread/694803

The culprit: Flash Builder doesn't work well with m2eclipse. Importing flex project as maven project confused the crap out of flash builder.
So what I end up doing is to start with clean project checkout, then in eclipse, create a new flex project with the same name as the checked out project, uncheck the "default project location" and point it to where the project is checked out. then tweak the src folder and build path to make the new project look just like "we imported it from the SCM checkout". After that content assist works like a charm.

Monday, March 14, 2011

NavigableMap in JDK6

JDK6 introduced NavigableMap and retro-fitted TreeMap to implement this interface. I was a bit confused at first about ceilingKey vs higherKey and floorKey vs lowerKey. It turns out that floor and ceiling operations can return equal entries, while higher and lower operations must be strictly less than or greater than.


Nice features. I can definitely find some uses for them. :)

Tuesday, November 23, 2010

Use compiler to catch new enum value not covered in "switch"

This old trick shines more and more when our project's code base grew over million+ lines. I have to put it on the web one more time just in case there is a developer out there haven't seen this.

Basically you can set the compiler to generate compilation errors when there are enum values not covered in switch block. So that when a new value is added to an enum class, every switch statement on this enum class will get a compilation error. This way it is easier to find and add corresponding cases, and it is impossible to ignore them. :)

To make this work, you have to do (or not do) two things:

  1. DO NOT use "default" case when you do switch on enum values.
  2. Set your compiler to generate ERROR instead of ignore enum values not covered in switch. In eclipse (the greatest IDE), it is here:

Thursday, February 25, 2010

hey gmail, what is up? I am a little worried about you.

I am a loyal fan of gmail ever since its first beta version. I jumped all over the web to get an invitation back in 2004. A couple years ago when my geeky friends switched their companies' email system to gmail, I was a supporter too.

But a couple things happened recently, which made me not so sure no more. Starting later last year I began to receive emails sent to another address that I had no relation with. Apparently gmail is forwarding others email into my inbox, all junk though. But if it is doing this, how do I know it is not forwarding my email to others?

Another hiccup happened this week. I pop emails from several alias accounts. And mails start showing up late, 2 or 3 days late, as a consequence I wasn't able to get back to people in time.

Google pretty much runs my life. I wish the best for them. But with the buzz burns still all over the web, this kind of misbehaviours on email application is worrisome. Even the giant can bite more than it can chew, sometimes. So this is a shout out to the gmail team, check it out.

Tuesday, February 16, 2010

JBoss Tools Eclipse plugin content assist lessons

I learned a couple lessons in the process of making JBoss Tools Eclipse plug-in to do content assist (where you type ctrl-space to get code suggestions). This is mostly about JSF component libraries.

First of all, in order to get content assist for JSF components, you must have the TLD file in your class path. We are using Richfaces libraries, and all its components get content assist. The ones I had trouble with are jsf-core and jsf-html, the f: and h: tags by default. Oddly enough though, with all the JSF libraries I have on my class path, none of them had packaged the TLDs for these two. I made a jar file and put jsf-core.tld and jsf-html.tld in the META-INF folder to get this working.

Another lesson learned is that the name space URI has to match exactly with the TLD's. I mean exactly. Kind of obvious, but easy to miss when trouble shooting. I added Openfaces like this xmlns:o="http://openfaces.org" in the first place and it didn't work, because it is expecting a "/" at the end. So the correct syntax is xmlns:o="http://openfaces.org/"

Sunday, February 14, 2010

Build Synergy in a new ubuntu system

Had to jump through quite a few hoops to get synergy to compile on a fresh ubuntu 9.10 box, including gcc-cpp and libxtst stuff. The most annoying error message is the 'You must have the XTest library to build synergy' one, it just won't go away after I got all the xtest, libxtst, libxest, libxcb-xtest crap installed.

Well, here is all it takes: (copied from synergy-plus)

By the time I figured this out, I already moved on to synergy-plus, which is much easier.

Thursday, January 28, 2010

jQuery goodies that I will try in next project

jqGrid, the data grid plugin with editing, searching, paging, and a lot more features
http://www.trirand.com/blog/?page_id=5

iconDock, good idea to put a bunch of icon/buttons on the page
http://icon.cat/software/iconDock/0.8b/dock.html

Horizontal Accordion, just cool
http://www.portalzine.de/index?/Horizontal_Accordion

Tuesday, December 15, 2009

jboss tools 3.1M4 code assist/content assist not working with JSF core and html?

I was playing with jboss tools 3.1M4 and only found out that I am not getting content assist (CA) for the JSF core and html tags. All other namespaces work fine, like richfaces, seam, ajax4jsf etc. How could that be?

My first thought was that the TLDs for core and html are missing. So I manually added the core and html XSD into the XML catalog, restarted eclipse, didn't do it.

Next I found a couple wiki pages (here and here) talking about how content assist works in jboss tools 3.1. They are good how-to but not helping me out. I was ready to dive into the source code and examine the Knowledge Base CA processors.

Then something stroked my mind: is it because my project is not considered JSF projects? I right clicked my project and in the Jboss Tools menu selected "Add JSF Capabilities...", and voila, that made all the difference.

I spent about 3 hours trying to figure this out. This reminds me again: more often than not the solution is much simpler than one imagined.

Thursday, September 24, 2009

keep aventail vpn working after kernal upgrade

I made aventail vpn client working a while back, here is the note I made.
http://a-developers-notes.blogspot.com/2009/05/aventail-vpn-under-kubuntu-904-fixed.html


But after each kernel update, the client will break due to the new kernel comes with a newer version of the openssl library.

Luckily the aventail client is looking for a specific version of ssl library, 0.9.7 being specific. so it is easy to make it work again. Here are the scripts:

Voila, got vpn client again!

Tuesday, May 19, 2009

aventail vpn under k/ubuntu 9.04 fixed

Just fixed my vpn issue with kubuntu 9.04. Actually the solution is not limited to k/ubuntu, google results showed that several other distros have the same issue too.

The symptom: through the web client, I am able to login, get web access, then get web and client/server access, but the Aventail OnDemand Tunnel shows status error, without any details. Or in the binary console client, you got DoHandShake Failed message.

Ben Smith got a great post
which eventually helped me solve my issue. Several points to watch out:

  1. Most importantly, try to compile different versions of openssl if one version didn't work, not necessarily a newer version. I started with 0.9.8g, then tried 0.9.8k without luck, then tried 0.9.8i and it worked. Dont ask why becuase it's way over my head.
  2. Make sure your aventail binary client's version matches your vpn server's version
Hat off to Ben, :)

Thursday, January 29, 2009

JSF converter implementation notes

SEAM's built-in converters are big time-savers, especially the s:convertEntity and s:convertEnum. Now the needs of rolling out customized JSF converters are few and far between, I just want to jot down the patterns I had used in case I forget.


  1. take the entity's primary ID as string, and load it from persistence media by ID to convert back to object

  2. implement an algorithm that can encode the object into a unique string, and reconstruct the object by parsing the string

  3. Construct a map of strings and objects. Because converters are instantiated on demand, you have to save the map in a backing bean whose life-cycle spans over requests. The map is nested in the h:selectOneMenu component using f:attribute tag, so that the converter can get a handle of it.


SEAM Howto - end conversation and go back to the previous page

In web application it is often desirable to provide a "Cancel" button in a function area which will redirect the user back to the page they come from.

In SEAM if the function area is wrapped by a conversation, then there are two ways to archive this navigation effect, depending on whether or not you need to do clean up when ending the conversion.

If there is no clean up to be done, you can use s:link or s:button as shown in the example below. The action is invoked first. The view attribute is rendered if redirect did not happen after the action invocation.

If there is clean up to be done, you can archive this in pages.xml file with a navigation hack.




In your pages.xml:

Tuesday, June 03, 2008

upgrade JBoss Tools from 2.0.1 to 2.1.0

Since JBoss Tools is a drop in plugin, you just copy the files into eclipse/plugin folder to install, I wasn't able to figure out how to remove the old version. It may not matter to eclipse but it just doesn't feel right to have multiple versions hang around. I know you can switch back and forth among different versions. But how often do you switch back? Plus eclipse is not able to recognize 2.1.0 of JBoss Tools anyways.

After fiddling with eclipse plugin management UI for a bit, I lost my patient and went with the brutal force:


cd eclipse/plugin
ls -d org.jboss.tools.* | grep 2.0.1.GA | xargs rm -rf
So far so good. Everything is still working.

Please comment if you have a better way to upgrade JBoss Tools.

Thursday, May 29, 2008

screen resolution for k/ubuntu 8.0.4 hardy heron running on virtualbox

Just fixed a resolution issue for my ubuntu hardy heron guest system running in virtual box (host is kubuntu 8.0.4). The solution is based on this thread.

There are two things I changed in xorg.conf to make it work:

  1. find the video driver device second and add Driver "vboxvideo". see following:
    Section "Device"
    Identifier "Configured Video Device"
    Driver "vboxvideo"
    EndSection

  2. find the screen section and add a display subsection including the modes.
    Section "Screen"
    Identifier "Default Screen"
    Monitor "Configured Monitor"
    Device "Configured Video Device"
    SubSection "Display"
    Modes "1280x800" "1024x768" "800x600"
    EndSubSection
    EndSection
Voila! it works. The only drawback is that the auto-resize guest display function of virtual box doesn't work.

starting vmware server on ubuntu 8.0.4 hardy heron

It wasn't an easy task to get vmware server installed on my kubuntu 8.0.4 box with kernel 2.6.24-17. And after jumping through all those hoops and firing up vmware, I cannot start any virtual machined created. The message I am getting is: Unable to change virtual machine power state: The process exited with an error: End of error message.

After a couple fruitless google searches, I saw a post mentioning about the debug information. Then I went to "edit virtual machine settings" -> "options" -> "advanced" and enabled the "run with debug infor" option. Hah, I got the actual error right away.

It turned out to be that I installed the vmware server with "sudo" and it created a ".vmware" folder in my home folder with root:root permission. Changing the permission fixed my issue.

Ehh.

Monday, March 31, 2008

join lines in Eclipse 3.3

Many times a day when formatting/re-factoring code I join the next line of code to the end of current line. If it is java code, you can do ctrl-delete twice then insert a white space in between two lines. If it is xhtml file, two ctrl-delete will remove the opening tag of next line (at least in JBoss Tools editor), so a lot of times I just type delete key as fast as I can, Yuk. I cannot tell how much I miss 'J' in vi to join lines.

NOW in Eclipse 3.3, a new (new to me) shortcut ctrl-alt-j will do exactly what 'J' does in vi, joining two lines and put a white space in between. Command-alt-j on mac.

Try it and you will like it.

Thursday, March 20, 2008

Using SEAM i18n support to externalize strings

SEAM brings support of i18n in JSF applications to a whole new level. It is another show case of "convention over configuration" design philosophy. But its documentation misled me a little bit.

By default, the resource bundle used by Seam is named messages and so you'll need to define your labels in files named messages.properties, messages_en.properties, messages_en_AU.properties, etc. These files usually belong in the WEB-INF/classes directory.
By reading this paragraph, I thought that when all you want is to externalize some labels/strings in your application, you can just throw a file named messages.properties then start referencing resources using messages built-in component. It didn't work like that.
I also tried to force loading the resource bundle using tag core:resource-loader in components.xml file. It didn't work either.
Finally it turned out that you got to put the locale string in your file name although you don't care about locale at all. In my case I just renamed my file as messages_en.properties and everything worked.
I guess it makes sense in a way that a resource bundle got be associated with a locale. But won't it be nice to dump everything without an explicit locale into the default?

Monday, October 08, 2007

Kubuntu/ubuntu run command dialog doesn't run script.

I put together a Eclipse launch script to start eclipse with JDK 1.6 while my system's default JDK is 1.5. Some extra VM parameters are also used to make eclipse run a little bit faster because I live in it all day long.

The script loads Eclipse fine in bash console. But when I try to launch it from run command dialog by pressing Alt-F2, nothing happens. Eventually I figured out that the problem is in my launch script: I forgot to push "#!/bin/sh" at the beginning of the file.

I am not sure why nothing happens when the sha-bang '#!' is left out, but if you encounter something similar, it might be cause.

Wednesday, September 19, 2007

Saving datetime into database, what timezone is it in?

Moments ago I posted a review on Amazon.com and returned to the product's page, it shows the review was posted 7 hours ago. It seems like Amazon is having a timezone conversion issue.

I am not trying to pick on Amazon. The funny part is that right this afternoon I was asked by a coworker about what timezone a datetime column of our database table is in. Then we had a discussion about how to handle timezones.

Timezone in databases is a delicate issue, and a tricky one to fully understand. Conversion is one issue. Others issues include moving data between database servers running in different timezones, moving data between different database dialects, interpret archived data, etc.

In the past I tried a couple approaches besides blindly saving the Date object through JDBC regardless of the timezone information. In one application I converted the datetime property into UTC time before saving it. In another application I converted time into milliseconds and saved it into database as long number.

I don't have a clear understanding of the relationship among the JVM's timezone, the Date object's timezone, the database server's timezone, the Timestamp's timezone in JDBC result set, and the Datetime column's timezone is MS SQL Studio's result set.

I have the full intension to study this topic in depth and report back.

Stay tuned.