Shared or Static – Visual Basic vs Java?

MP900386814 In Java there are 2 fundamental concepts that any developer should know: instances and classes. Class its the base of your code, your specification about an entity, like Account, Customer or Supplier. Instance its what you get after a “new ” (an object in the heap). So you have at maximum 1 class and N instances of that class.

Although a class its just the specification, in Java a class could have state and behavior like an instance, but with the condition “There could be only one” shared for all instances! Everything that are declared as static are executed(static blocks for instance)/initialized at class load time by the JVM, the rest (instances) are executed/initialized in runtime, after load time.

This word, static comes from very long time, since C, C++, C# and others, but Visual Basic uses other word “shared which somehow implies the behavior of the fields declared as static(java) or shared(visual basic) after a Class “is running”! After the JVM has loaded your class, every static(java) field are shared(visual basic) between all instances, so the question is:

What of these words captures better this behavior (of static) “static” vs “shared”?

So, although I really like a lot languages like C++, Java and C#, I must admit Visual Basic its somehow more expressive and more closely related with the true meaning of “shared” fields!

The not so ACID transaction properties

If you work with Database Servers you know that ACID its not implemented/active by default! And if you have it implemented you have a really poor performance on your database server!

Lets examine each one of these properties:

A = Atomicity

Definition by wikipedia: “Atomicity requires that each transaction is “all or nothing”: if one part of the transaction fails, the entire transaction fails, and the database state is left unchanged. An atomic system must guarantee atomicity in each and every situation, including power failures, errors, and crashes.


– “… and the database state is left unchanged“. Unless you configure your database server with ISOLATION LEVEL SERIALIZABLE this is not true. By default most SGBD are configured with Read Commited, with allows some changes like phantom reads.

C = Consistency

Definition by wikipedia: “The consistency property ensures that any transaction will bring the database from one valid state to another. Any data written to the database must be valid according to all defined rules, including but not limited to constraintscascadestriggers, and any combination thereof.”

RIGHT for schema state, WRONG for value state (explained in atomicity above)

I = Isolation

Definition by wikipedia: “The isolation property ensures that the concurrent execution of transactions results in a system state that could have been obtained if transactions are executed serially, i.e. one after the other. Each transaction has to execute in total isolation i.e. if T1 and T2 are being executed concurrently then both of them should remain unaware of each other’s presence

WRONG! Only in dreams! its possible, yes, but in the way you encounter DEADLOCKS and Poor performance. If you want a performance database server you must drop the isolation to the lowest level possible! Its the price to pay for having fewer locks in the middle of your transactions.

D = Durability

Definition by wikipedia: “Durability means that once a transaction has been committed, it will remain so, even in the event of power loss, crashes, or errors. In a relational database, for instance, once a group of SQL statements execute, the results need to be stored permanently (even if the database crashes immediately thereafter).”

RIGHT! Well, I give this one, and I’m glad I could, what was a database server without it! 😉 However, actual high performant database servers have some kind of memory cache where there is a risk of loosing data, but, as far as my knowledge goes, it only happens in some NoSql databases… I hope…




What I dont like about Java Application Servers

I have a lot of experience with Java Application Servers, from Weblogic to jBoss 5,6,7 and Glassfish. I’m a Java and J2EE Trainer too. So, I’m not here to make an argument against the use of Java Application Servers, I use them every day, however I must say some things that I really dont understand (from a user/developer perspective) about Java Application Servers:

Why Java Application Servers don’t isolate a deployed application? How many times are you deploying an application and you have to configure, customize, remove jars, add another’s jars, create additional files just because the application server already has some of the jars you use in your application? For instance, in my team, we are migrating sites and web services from weblogic and its a nightmare, jboss already have some of the jars, and at deployment time throws exceptions that are not so easy to understand at first sight. (like logging jars – in our case slf4g with logback) If an application could be isolated like a file system application its isolated in an operating system like linux or MAC OS these problems dont even existed! I just wanted to deploy my application with the jars I need, and don’t think about what jars the application already have.

I have experienced deploying applications in Microsoft IIS and in Java application servers. Using Microsoft Servers its much more easy than using similar java products. Usually, when starting and developing Microsoft products I spend 80% of the time focused in developing and  testing the product, and the other 20% finishing configuring and deployment. With Java Application Servers, first you must study the application server, know about several XML files with specific names, to configure datasources, jms queues, etc. Then you hope that exists some eclipse plugin or netbeans plugin that really works. I have experienced plugins for weblogic and jboss but sometimes when you deploy an application its just a view for your eyes, the application doesnt get really deployed to the application server, so I have to go to the localhost website, and deploy it. The inverse its also true. So, 80% configuring and preparing, learning and training and the rest 20% of time developing.

Don’t get me wrong, my experience its divided between these two worlds (Microsoft and Java), I like Java, after all the configuration its done everything will work as expected, but its a really tough job to put everything to work at first in Java Application Servers World!


Do you know ForkJoinPool Java 7?

Java 7 brings and/or improves thread management to handle heavy and complex tasks.

You can use threads, ExecutorServices and this: ForkJoinPool.

There is an increasing developers movement to coding in a functional state of mind, using Ruby, Scala, Clojure and other similar programming languages. Java 8 will follow this path too, with lambdas. If you are not using a functional approach in programming, I invite you to do so, its a very different way of thinking where the “divide to conquer” its a must!

In Java 7 you can use this way of thinking to resolve complicated problems, the ones where its necessary to think recursively where you can split a heavy task in simples ones, like when you are sorting a big list using quick sort, transverse a file system including every folder and file, etc. These are problems that seems complicated at first, but thinking recursively it turns out to be very simple tasks.

The main algorithm to implement a recursively task its always something like:

  1. What is the stop condition? (Here you return a “real” value)
  2. Call the method recursively calling it itself with some sort of improvement in the parameters, like if you are in a for.. loop.

For instance, long factorial(long n)

  1. stop condition: if( n <= 1) return 1;
  2. calling recursively like a loop: return n * factorial(n-1)

Has you know by now, the factorial(n-1) will have to stop in the future, because n-1 its decreasing until it reaches  n <= 1, and then n * will be really calculated!


In Java 7 you have a Class ForkJoinPool that automatically handle threads to execute the smaller tasks like the above: n and  factorial(n-1).

The recursively method will always be the protected Long compute(), which must be an @override because the class will extend: RecursiveTask, where will be the return value of the compute method!

In the example below, I have implemented a very simple example to calculate the sum between 2 numbers, using recursive smaller tasks.

I start with some range, if the stop condition (end – start), its below 10, then I return the sum between the start and end, otherwise I split the range in 2 parts, the first one executes concurrently (using fork witch puts the thread in the ForkJoinPool) the second half of (end – start) and the first one computes the sum delegating its execution to the compute method (itself!), or the other half.

Observe the last return: return t2.compute() + t1.join(); where the second thread calls the compute and then waits for the fork previously executed as the first thread!


I think the code its very clear and simple, if you have questions or comments don’t hesitate to post them!

This Is a very useful tool to resolve complex problems that I really invite you to learn and use it!

Gamification in the family

One of these days I went out to lunch with my family. My daughter does not like to eat, it is complicated to sit an entire meal just to eat. But there’s something she likes, games, play them on my wife’s iPad, on my iPhone, Laptop, etc.. Why not apply gamification with my daughter, since I am a gamification evangelist? She was eating steak with chips and a juice that she likes a lot. The juice was already halfway. So I proposed the following game: For every 5 chips and 3 pieces of steak she could drink a sip of juice. It worked, ate almost everything!
The meat and potatoes were the points, my daughter was the player whose behavior I wanted to change, the juice was the package of rewards!
One of these days I’ll play another … several meals completed, and give her a “Badge” (probably a Winx doll or other toy that she can show to her friends as a prize!)

Gamification and Reality

One great video with a possible future in these areas!

Sight from Sight Systems on Vimeo.

jBoss 7 – Web service client – popular exception “definitions”

In the process of migrating some J2EE Applications from Weblogic to jBoss 7 I’ve been found several issues that puts the popular java statement “Write once run everywhere” in cause. I will not start here any discussion about this, if the cause its j2ee, jboss, weblogic, axis, although you are free to do it so, and I will have arguments pro and con, but it was not so smooth as I was expecting it to be.

One of the last errors that toke me some time to figure it out, and I found the solution by intuition trial and error was when I had to generate a web service client for a jBoss j2ee appilcation that works great in weblogic but in jboss throws the following error when calling a web service:

… several stack trace lines but the main one:

… at some point in the stack trace

Caused by: javax.wsdl.WSDLException: WSDLException (at /html): faultCode=INVALID_WSDL: Expected element ‘{}definitions’.

So, I’ve tried every possible solution, from generating different kinds of web service clients, using Axis, jboss, CFX, to changing Jaxb versions on eclipse facets to 2.0, 2.1, 2.2.

About the solution:

In the construction of the web service call

MyWebService_Service service1 = MyWebService_Service(new URL(wsdl));
MyWebService port1 = service1.getMyWebServicePort();


In Weblogic a possible URL could be passed on the web service class constructor as :

– “

But In jBoss, the URL must use the “?wsdl” at the end of the url! like this:

– “


I dont know why, maybe when I have time I can discover the reason, but for know it was the solution I’ve found for this kind of exception that apparently its a popular problem around forums.

Hope my solution can help you anyway, or if you find another reason for this exception, be my guest to put it on the comments area!

Gamificação: Mecânica, Estética, História e Tecnologia – Parte III

small_339901660 A Tecnologia é um dos componentes tecnicamente mais exigentes e que exige acima de tudo pessoas especializadas, engenheiros de software, hardware, etc. No caso de um Jogo tal como os conhecemos como Playstation, XBox, PC,  poderá resolver-se com pessoas com skills em programação de software, pois os controlos remotos, aparelhos, televisões, etc já estão todos desenvolvidos. No entanto, não quer dizer que fiquemos por aqui, pois começa a surgir acessórios externos que tornam a experiência no Jogo muito mais enriquecedora, como animais de estimação mecânicos que são controlados por wireless após acções no jogo que é projectado na televisão, até à experiência de existir uma cãmara que identifica os nossos movimentos e transforma-os em acções na mecânica do Jogo, como no caso de Jogos desportivos e fitness. A tecnologia por si só não resolve nada, podem-se fazer Jogos com uma complexidade tecnologia enorme, com acessórios de tecnologia de ponta e o Jogo ser um fracasso, há que considerar sempre os outros 3 pontos (Mecânica, Estética, História). No entanto, este é um assunto que hei-de referir no futuro sobre o efeito holistico de juntar estes 4 elementos constituintes do Jogo e como juntamente com um Tema pode criar uma sinergia fantástica na experiência final.

Na Gamificação de um web site (tipicamente uso o web site pois é um exemplo que foge radicalmente ao conceito de Jogar tal como conhecemos num aparelho de jogos) o que é a tecnologia? Os conceitos dos jogos aplicam-se perfeitamente na Gamificação, o próprio nome o indica, e no caso da tecnologia isso não muda, no entanto, enquanto que quando compramos um Jogo a tecnologia já lá está, até para quem o faz metade já foi preparado (os aparelhos, comandos, acessórios) no caso de um web site, há que fazer ou mexer no web site e criar “o aparelho” e os comandos!

O “Aparelho” para o Jogo terá que ter vários componentes:

– um pacote de software que consiga monitorizar os “movimentos das jogadas” do utilizador, como que links visitou, que comentários fez, que rating deu nos comentários, que outros utilizadores recomendou e chegaram ao site, enfim, que jogadas anda a fazer na mecânica do nosso jogo.small_6105644516

– um pacote de software, que já foi definido previamente com a mecânica do jogo, que  pega nas jogadas que estão a ser feitas, valida os movimentos (regras do jogo) e promove as consequências, como prémios, pontos, passagem de níveis, etc, que num web site poderão ser ofertas de assinaturas, distinção em homepages desportivas, de secções de notícias, aparecer em primeiro num grupo de comentários, leaderboards, badges, e outros virtual goods. (embora aqui já estou a entrar um pouco na estética e nos PBL – pontos, badges e leaderboards que pretendo discutir futuramente).

– as alterações ou definições no design e interacções com o site. O site além do seu design com a sua informação terá também que contemplar como se fizesse parte dele inicialmente os componentes da gamificação e por isso a tecnologia a escolher é uma peça muito importante, porque um site informativo poderia estar apenas em html/css/javascritpt, com gamificação terá que ter elementos mais dinâmicos e de programação mais avançada, afim de poder receber “as jogadas” dos utilizadores, e poder reagir ao avanços ou recuos consequentes dessas jogadas. Basicamente tem de estar preparado para se ligar ao “aparelho de jogo” falado atrás.

Assim, quando se quer gamificar um site, ou outro componentes de software, quer desde a sua criação ou alterar algo que já existe é necessária alguma consultoria técnica mais avançada como um consultor sénior de software. Sem ele poderão ser tomadas decisões acerca do Jogo que poderão não ser possiveis mais tarde implementar, tal como alguém quer um Jogo com um visual completamente real como o filme Avatar mas a tecnologia ainda não chegar lá! (No caso do filme Avatar demorou alguns ANOS para se conseguir! embora parecendo no produto final algo tão simples!)

O tema da Tecnologia, que é um tema que certamente voltarei a referir no futuro com mais profundidade, com exemplo não só de software, é muito importante, pois acima de tudo um projecto de software que queria ter elementos de Gamificação deve incluir como seus requisitos os requisitos da Gamificação no mesmo nível que os restantes requisitos do projecto, porque afinal de contas a Gamificação é um dos contribuintes para a melhoria do negócio!

photo credit: toughkidcst via photopin cc

photo credit: h.koppdelaney via photopin cc

WordPress Cache, Hyper Cache, Super Cache, W3 Total Cache

One of these days a customer asked me to improve the performance of his wordpress website. The first thing I’ve done was to measure the actual performance of the site. For that I started to search for firefox and chrome addons. I’ve already knew a few, bur after some googling I found that the usual suspects were enough: Firebug with YSlow and Google Speed Tracer. There were anothers but I couldnt find any reason to use them.

So my first metrics of the web site from the YSlow:

1) Homepage on first call without cache retrieves to client about 1800Kb
2) After first call, the most part of webpage elements stay on browser local cache, like 700Kb of images, 500 of Javascript and CSS and the rest was Html. So, to the client just comes 120Kb. Not bad at all! But not the 100Kb recomended pratice.

So, I want to reduce below the 100kb, and who knows the 1800Kb too, How?
I started to search for a wordpress cache plugin to compress (using http compression, which was one of the recomendations from the performance analysis tools) html, javascript, css. I want the website to respond faster instead of always using the access to the wordpress database to retrieve the same content (the posts arent always changing!). Besides these reasons, its helps for google SEO/rank faster webpage retievals. I found 3 plugins:

  • W3 Total Cache
  • Super Cache
  • Hyper Cache

Apparently the best one was suppose to be W3 Total Cache. Great reviews, very popular, but wih one biggest problem, doesnt work well in WordPress 3.4.x, just works until 3.2.x. Unfortunelly I had to put it aside.
So I had to find which one of the others I will choose.
Both are very similar, but after some search, reading, analysis of performance with cpu and memory charts the Hyper Cache was found the best, more lighty, works great in WordPress 3.4.x and its realy very easy to use, I just had to define Cache on wp-config.php.

So I’ve installed the Hyper Cache Plugin and tested the website performance and the quantity of kbytes transfered to the browser. Well, at first, the length was the same, but after reading the Hyper Cache Help I discovered that when I am logged as wordpress admin, the Hyper Cache its disabled, so any test will be with no use or conclusion. So I started a session with another browser without any website cookies for the site I was using the Cache and at the first test, even the 120Kbytes was reduced to 80Kbytes, and the 1800kb reduced at first attempt to 1600Kbytes (images are images, the wordpress cache cant do anything about it).

I hope this experience can help anyone struggling with ways to improve the wordpress performance in wordpress version 3.4.x.

Gamificação: Mecânica, Estética, História e Tecnologia – Parte II

Num dos meus últimos posts falei da relevância da História na criação de um jogo, seja ele para gamificar um site, criar realmente um jogo ou uma aplicação para um smartphone, tablet ou pc. Hoje irei abordar a Mecânica do Jogo.

chess O que é a Mecânica do Jogo? A mecânica do Jogo são as regras, surpresas, caminhos possiveis, acções, objectivos de vitória, ganhar vidas, conquistar, etc que vemos num jogo. São as restricções e ao mesmo tempo o nosso playground, ou seja, o espaço onde decorre o jogo segundo um conjunto de “regras”. Um exemplo simples: Xadrez! As regras são claras: pode ser jogado por 2 jogadores, um com peças brancas outro com as pretas. Cada jogador tem um conjunto de peças que se movem sob determinadas regras (num tabuleiro de 64 casas brancas e petras), e os seus próprios movimentos por vezes estão constrangidos à posição de outras peças (um peça não se pode mover se isso matar o seu próprio rei), do adversário ou da própria Estética(casas brancas e pretas. Num posto futuro falarei sobre a Estética do Jogo) do tabuleiro. O objectivo é ou dar mate ao rei adversário ou empatar quando não é possivel a vitória.bookstore

Um outro exemplo fora do âmbito dos jogos puros poderá ser um web site.  Uma estratégia para atrair utilizadores a um site gamificado (ou não) é recompensa-los quando estes recomendam alguém e essa pessoa volta ao site. Esta estratégia é por exemplo usada pela Dropbox, que oferece mais X GBytes de espaço quando alguém vem por convite e mais ainda se essa pessoa comprar mais espaço. Vamos supor que o site é sobre compras de livros digitais, também serve para outros produtos, e estou quase a chegar ao nível 2 do site, onde me é dado 5% de desconto permanente, mas para isso preciso de mais 100 pontos que consigo com 10 novos registos de utilizadores no web site que comentem livros pelo menos 1 vez. Além disto, sou reconhecido no site quando atinjo X recomendações sociais! Toda esta descrição faz parte da mecânica do jogo no site, “obriga-me” a trazer clientes, fazendo-me progredir no “Jogo” que por sua vez me traz recompensa pessoal. (Espantoso como a Gamificação faz as coisas andarem para a frente e ajuda o marketing de uma forma sensacional!).

Trazendo de volta o post anterior, qual seria a história para um web site de venda de livros gamificado? Poderia ser contada juntando a missão da empresa na venda dos livros, algo como servir o livro certo para as expectativas dos clientes, e ao mesmo tempo criar “aventuras” sobre determinados temas dos livros para os quais os utilizadores/clientes gostassem de comentar e dar as suas opiniões sobre os mesmos. Possivelmente, o número de comentários, o número de recomendações e o número de comentários bem avaliados seriam possivel fontes de pontos para promoções, descontos, badges, recompensas, etc. Os níveis seriam os descontos, que seriam também rewards ou recompensas, e um leaderboard de especialistas sobre temas no site! (Acho que já entrei demais na estratégia do marketing para um web site, mas foi para o bem da mecânica!).

Se a história é a descrição do mundo do jogo, a mecânica é sem dúvida a criação “física” desse mundo e como podemos “jogar” nele.


photo credit: szeke via photopin cc photo credit: EricGjerde via photopin cc

Bad Behavior has blocked 174 access attempts in the last 7 days.

Hyper Smash