Search posterous

Search all posts and users. Type a name, type a favorite song title, whatever! See what comes up.
  

More posterous blogs











More recommended blogs »

Here are posterous posts filed under java...

Matt says...

the biggest news was probably the timeframe announcement for Apache Tomcat version 7.  According to Jim Jagielski, chairman of the Apache board of directors, Tomcat is used in at least 75% of Java-based websites.  Mark Thomas, a member of the Apache Tomcat Project Management Committee, said that the alpha release of Tomcat 7 is expected in December 2009 or January 2010.  DZone spoke with Thomas for an exclusive interview about the upcoming version of Tomcat. 

Cool new stuff coming in Tomcat 7, and I didn't realize an alpha was so close.

Filed under: Java, Tomcat

Oz says...

The base javascript framewotk of Gmail, Google Docs and more.

Where I found it:
http://ajaxian.com/archives/google-releases-closure-the-tools-behind-the-js-geniuses
Go here for a quick overview

Introduction From the makers:
http://googlecode.blogspot.com/2009/11/introducing-closure-tools.html
Go here for an introduction made by the team who made it

Official page:
http://code.google.com/closure/
Get it here ... And read the details of each module

Nice fact
They Work in Google and almost every module came out of 20% Project wich is an idea I think is great!

Filed under: closure, frameworks, google, java, javascript, programming

riduidel says...

Pour mon nouveau boulot, je suis amené à faire du Flex. Je ne le prends pas trop mal, dans la mesure où ça me permet (en théorie) d'implémenter un point essentiel des méthodes pour rester un développeur "on the edge".
Là où c'est moins bien, c'est que tant qu'à faire, j'aurais préféré travailler sur un langage qui ne fasse pas semblant.
Prenez l'IDE, par exemple. La toute dernière version de Flash Builder est en fait un packaging d'Eclipse dédié aux développeurs Flash (comme peut l'être, je ne sais pas moi, Eclipse for C, Pulsar, ...). En un sens, c'est très bien, parce qu'en tant que développeur Java, je ne suis pas vraiment surpris. Sauf quand ils décident de me livrer sans mon consentement une version française. Ou que le seul refactoring disponible soit le renommage de fichiers (alors que faire des refactorings dans un langage dynamique, même si c'est plus difficile, c'est possible). Ou que les erreurs de compilation me font revenir quinze ans en arrière, avec des codes aabscons suivis de messages encore moins clairs (pour l'anecdote, il m'a fallu hier à peu près l'après-midi pour trouver qu'un test ne fonctionnait pas à cause d'un simple problème de déclaration de constructeur). Ou qu'une application mxml contenant les tests doive se trouver dans le dossier src (ce qui est super pratique pour séparer les tests et le code source de ma bibliothèque, tiens, imaginez comme maven est content).
Et si l'IDE infâme ne vous suffit pas, prenez les bibliothèques de test unitaire. En Java, je connais bien jUnit, et un peu TestNG. Elles sont plutôt documentées et facilement intégrées dans l'IDE. Bon, en Flex, il y a quoi ? flexunit ? funit ? asUnit ? bon, eh bien je vous mets au défi de trouver une doc claire et complète pour ces différentes bibliothèques; Attention, je ne parle pas d'un tutorial écrit pour faire comme tout le monde et présentant un exemple bidon même pas intégré à l'IDE, mais bien de l'exemple complet qui me permet à la fin de lancer mes tests dans l'IDE. Cherchez pas, vous ne trouverez rien. Parce que ces trucs sont codés à la va-vite et que leurs auteurs ne semblent pas se soucier de l'industrialsiation de ces tests unitaires.
Et pour finir avec l'industrialisation, parlons un peu des flexmojos. C'est une super-idée de vouloir intégrer la compilation Flex à maven pour montrer comme l'outil est extensible. Mais c'est aussi une terriblement moins bonne idée que de fournir une dépendance flexmojos-unittest-support qui contienne les trois bibliothèques sus-mentionnées (dont les classes de bases de test unitaire s'appellent toutes ... TestCase ... merci pour les problèmes d'import) sans jamais expliquer comment éviter cette dépendance (mis à part, quand on connait maven, en allanrt faire un tour dans le pom de cette dépendance pour trouver les dépendances initiales et leurs versions respectives).
Bref, Flex, c'est quand même vachement moins bien que Java. Et c'est là que je comprend les éternels regrets des vrais développeurs Java, qui voient Sun lancer des idées du bout du petit doigt et ne pas les soutenir (au hasard, JavaFX) alors qu'avec un bon soutien, cette techno a les moyens de botter cent fois les fesses à ce Flex, qui n'est rien d'autre qu'un javascript vaguement rabhillé.

Filed under: flex, humeur, java, test

riduidel says...

Ces temps-ci, comme vous le savez peut-être, je ne fais plus vraiment beaucoup de Java.
Pour m'entretenir, je me suis donc dit que j'allais voir dans quelle mesure mon idée folle était réaliste ou pas. Et pour ça, évidement, la meilleure solution, c'est de tenter une implémentation "POC", c'est-à-dire pas belle, mais qui fasse tout ce que je veux.
Et je découvre avec stupéfaction que le monde ne s'est pas arrêté il y a deux ans, et qu'il y a toujours des mecs qui développent des bibliothèques très pratiques en java. Oh, bien sûr, quand il faut les inclure dans une application Java Web Start, ça augmente les temps de download. Mais je vais vous dire, depuis environ 2 ou 3 mois, faire le JAR le plus petit du monde, ça ne m'intéresse plus. Surtout quand la contrepartie, c'est l'interdiction d'utiliser la moindre ligne de code étrangère. Et donc, j'utilise des bibliothèques externes, avec joie, devrais-je dire.
J'ai donc découvert des trucs très bien, comme
  • Guice, que je connaissais déja de vue, mais qui est vraiment très agréable quand on peut réellement utiliser l'introspection.
  • glazed-lists, avec lequel je commence tout juste mes expérimentations, me paraît mériter plus qu'un coup d'oeil, tant il peut rendre de services (et éviter de réimplémentations fastidieuses).
  • google collections et guava m'ont l'air de pouvoir amener quelques jolis éléments d'écriture à la limite de la programmation fonctionnelle (ce qui va nettement me rapprocher de Ruby, et dans le meilleur sens du terme).
  • De manière plus anecdotique, jintellitype eest aussi sympatoche.
  • Et bien sûr, commons-configuration, qui devrait me permettre d'éviter (enfin) de redéfinir mon  propre format de propriétés.
Enfin, de mani-ère encore plus latérale, une fois que j'aurais fini l'implémentation Java de mon idée folle, je tenterai peut-être un truc fou : en refa

Aaaaaaaaah ! Saloperie de clavier !

J'ai accidentellement tapé sur CTRL-machin qui a envoyé le mail ! 

Bref, je disais donc, en refaire une partie en Griffon. Ca a l'air de permettre des choses assez mignonnes, et de manière très efficace (sans doute grâce à Groovy dont je m'imprègnerai aussi, et puis ça me fera mon langage de 2009/2010). 
Mais pour l'instant, je joue pas mal avec la complétion via glazed-lists, et c'est franchement chouette. 

Filed under: dev, java

pinxystech says...

My new project hasn't been any exciting, I kept wondering what on earth was I doing. I ha dto deal with on-boarding Apps day after day on to Hudson and get the Sonar Metrics up. Lame I thought, it was dreadfullu monotonous , until I hit this one. It was a simple Java Heap size issue and I rather sheepishly , set the Hepa to the maz 1024 , no luck. I then bumped it to 2048, still the issue refused to die down. Huh! I targeted the GC options on a lead's suggestion, 2 days + a gazzillion permutations and combinations, I almost gave up.But I guess I mastered the  GC quite a bit.

One look at the build file, the fork option was set to Yes and we had to set up the heap size for each fork here insteda of the usual way of setting it up in the Hudson console. A simple solution , a simpler problem, I just refused to look at the right place.

fork=”true”
memoryInitialSize="256m"
memoryMaximumSize="1024m"

 

Filed under: Fork, Heap, java, java Heap size

EastsideRJ says...

We tried doing the direct inject into the arm veins of test subjects and things didn't go so well.  But this oral inject method has been tested and is safe for all ages.  Current prototype will be available for sale very soon.  Say goodbye to-go cups.  Say hello drug paraphernalia.  Remember, do not share needles with anyone.


(you too can post to this blog as a member of Team Twitter.  Just check the Terms of Use.

Filed under: buzzed, caffeine, coffee, eastsiderj, inject, java, syringe, team twitter

dhanji says...

"By the pricking of my thumbs, something wicked this way comes."

-- Macbeth, act iv

In almost all modern programming languages, you have this thing called Memory Management. Roughly speaking, it is the art of doing that which by any other engineering standard, would be considered procrastination. Your application allocates heap space and as desired and leaves the cleaning up for later.

And the clean up is done by a magic, little black box known as the Garbage Collector. Its workings are intricate and complex. There are sometimes good reasons for this complexity, and often not. If you are a Java programmer (or use JVM languages like Scala), you should know a few basic things about this mysterious beast. And these few things should put the fear of God into you.

Stop the world

The first, and sometimes most perplexing fact about Garbage collection in the JVM is that when it decides to reclaim memory all application threads are stopped. It doesn't wait for requests to complete, transactions to commit, nor for you to pass go and collect $200. When the GC decides to kick in, your program stops. The more objects you create, the longer this pause lasts, and the longer it lasts, the greater your risk of timing out connections, losing data and generally making things very bad for your users. This problem cannot be solved, it can only be mitigated. You must learn to live with it.

How the generational collector works

There are two generations (of interest), young and old. As their names imply, they are intended to house either flavor of object. This is often where you can get tripped. The Young Generation is a fast, short-lived space, operated by a copying collector. A copying collector works like this:

  • You divide the memory into two equal spaces. 
  • Allocate objects in the first one until it fills up.
  • Now, you stop the world, scanning for live objects and copy them to the second space.
  • Then, start allocating from what's left of the second space.
  • Lather, rinse, repeat
Now, copying collectors are very fast--especially if most of your data is garbage. This is because it copies just the surviving objects and discards a whole memory space at once. However, this comes at a rather large cost--one half of the memory is always useless.
Of course the JVM is a bit cleverer about it, and uses one very large allocation space (called Eden) and two smallish survivor partitions, swapping between them. So in practice this is not as great a problem. One of these cycles is called a minor collection, and they typically last in the milliseconds.

How the old generation works

Once objects have been copied a lot between the Eden and survivor spaces, the JVM decides that it is too expensive to keep copying them around since they don't seem to be dying at all. At this point it promotes the object by copying it to the old generation. This process is called tenuring and is intended to detect very long-lived objects such as singletons and data constants.

The old generation uses a much more memory efficient collector and is typically much larger in size than its young counterpart. It uses a compacting collector that works like this:
  • Stop all application threads
  • Perform a thorough analysis of live memory (including soft/weak refs)
  • Copy all live objects to the beginning of the memory space ("defragment" it)
  • Start allocation after the last live object, thus freeing up everything that was not copied
This process is known as compaction and is comparatively very slow (runs in the seconds). It is very similar to disk defragmentation, which you may be familiar with from MS DOS days. This is sometimes called a full or major collection. The slowness and impact of a full collection cannot be overstated. While it is running, your application is basically dead in the water.

Reducing the frequency and duration of the aforementioned cycles is a dark art, worthy of the most occult of bit-sorcerers.

The Four Banes of Murphy

The following are four nemeses to the unwitting Java programmer, who in her blissful exuberance and naivete, believes that automatic memory management somehow means not having to worry about managing memory.

The GC spiral of death

So, the generational collector at first glance seems like a wonderful compromise between optimizing for short and long-lived objects with a tradeoff for speed and memory respectively. At second glance however, this is one of the most notoriously difficult things to predict and control. Almost all poor GC performance comes from misunderstanding this in some way.

Take the following scenario: When the application is under light load, short-lived objects are allocated and destroyed in the young generation as quickly as needed. The JVM observes this memory usage pattern and decides to set the young generation at a smallish size. Now, you suddenly experience heavy load, and this means thousands if not tens of thousands of short-lived objects suddenly all start clamoring for memory. To keep things going, the GC overflows these short-lived objects to the old generation, where there is still plenty of space. So far, so good.

However, recall that the old generation only gets cleared in a full GC cycle--which means that you need to have much more frequent full cycles, causing more frequent and longer pauses (seconds' worth) under heavy load.

Now, if the load remains heavy, these objects are continually overflowing and the GC's adaptive sizer notices that the old generation is in much heavier use. It decides to increase the size of the old generation accordingly. By complement, this means decreasing the size of the young generation, causing further overflows, and still slower and more frequent full cycles where the application is completely paused. As a result, your users see slow or unresponsive GUI elements and they start repeating commands (have you ever stood at a DONT WALK sign and hammered the button?), or worse they reload the entire app, producing greater load and an even greater stress on the JVM. Eventually, your application is completely unresponsive and you start losing data, timing out connections, and are forced to kill the process.

Soft references are the Devil

The SoftReference class should really have been called the SuccubusReference, because that's what it is--a seductress of meretricious and superficial beauty, who will drag your soul to hell and leave your corporeal body a listless shell, exhausted and empty.

Soft references are often touted as a convenient way to write caches. They are similar to weak references in that the GC will clear them if they are no longer needed by any active parts of the program (in technical terms, if they are not reachable from heap roots). However, they differ from weak references in that the GC will not clear them until it determines that it is running out of memory. They are also cleared in order of staleness. If you have worked with caches before, you know that it is next to impossible to write an accurate LRU cache that is also highly concurrent. So if the JVM provides these for free, why not use them? Here's why not:
  • SoftRefs use the timestamp of the last full GC cycle. Under memory pressure, this means you will have to wait for the next full GC cycle to get rid of them. Meaning that the JVM can run out of memory and die, even while there are soft references yet to be cleared.
  • They are incredibly difficult to profile, since taking a heap dump will trigger a full GC cycle, and clear them.
  • You cannot accurately predict when a SoftRef will be cleared, nor can you easily bound the size of a SoftRef cache.
  • Using them in critical code is dangerous because you are giving up control of your program's behavior to the whims and quirks of the Garbage Collector.
For these reasons, I recommend against using them at all.

The Vacuous shall inherit the earth

What's wrong with this code sequence?
  1. Start with a HashMap using new HashMap<K, V>().
  2. Over time, put a largish number of values in it,
  3. Over still more time, remove a number of entries.
Two things are wrong:
  • The HashMap starts with an initial capacity of 16. Each time you exceed its capacity it must resize the underlying array, which is wastes memory and is slow.
  • At step #3 the map is largely empty and is wasting a huge amount of memory, eventually causing memory pressure.
What's wrong with this (almost opposite) code sequence?
  1. Start with a HashMap using new HashMap<K, V>(),
  2. Put a small number of entries in (but, don't remove any).
Now, if you use this pattern in your data model, you could end up with thousands or even millions of partly empty arrays. This all adds up to wasted space, and at crunch time, it will kill your application.

Fix this problem by estimating the size of maps and lists beforehand and by trimming down long-lived or cached data structures over their lifespan. Calling new HashMap<K, V>() is several times more efficient than calling map.clear() for even mid-sized maps. Don't fear that you are creating more work for the GC--remember that collecting dead memory is a constant time operation. Marking live memory on the other hand, is not. I simply cannot overstate the impact of this problem.

The JDK and collections libraries in the wild do not take this concern seriously enough, in my opinion.

JIT and the GC

So you wouldn't think it, but Sun's Hotspot just-in-time compiler actually has an effect on Garbage Collection efficiency. This is because of an interesting feature where marking paths are optimized in compiled methods. In the -server JVM, methods are not compiled until 10,000 invocations, which can take several hours or days depending on server load. During this time, profiling GC behavior can be misleading and potentially draw you to erroneous conclusions. So be wary of this.

There is also a strange flag: -XX:DontCompileHugeMethods, which is on by default (meaning it doesn't compile huge methods, unless you tell it to). For such large methods, if they are hot, you may incur a GC penalty.

Conclusion

If learning all this about Garbage Collection does not cause you the utmost of terrors, and the eternal loss of sleep (as it did for me), then go back to the top, and read this article again until it does. =) 

"Glamis hath murder'd sleep, and therefore Cawdor shall sleep no more; Macbeth shall sleep no more."

-- Macbeth, act ii

Update: In all references to JVMs above, I am referring to Sun's Hotspot JVM as of version 6.0.

Filed under: caching, garbage collection, gc, java, jvm, macbeth, softreference

spruiked says...

Landslide-prone areas in Central Java have risen from 97 to 135 districts due to uncontrolled land conversion and forest encroachment

501 villages in Central Java are "land-slide prone". What that means is that there is a danger of people being killed or injured if there is an earthquake or heavy rain. Landslides were the biggest single killer in the Padang earthquake last month.

Landslides are caused by over-developing unstable land, or clearing trees from slopes. As Indonesia's population grows, its towns expand into areas which, quite frankly, shouldn't be developed.

Remember, earthquakes don't kill people. People kill people by building shoddy structures and by building on unstable land.

Filed under: earthquake, java

Quân says...

- Modify service layer 

modify the SimpleProductManager and add a reference to a ProductDao
'springapp/service/SimpleProductManager.java'

- remove the productManager configuration and the list of products from the springapp-servlet.xml
- configure the service layer in its own application context file 'applicationContext.xml'.
It will be loaded via a servlet listener that we will define in 'web.xml'

- 'springapp/web/WEB-INF/applicationContext.xml'

- using AOP (Aspect Oriented Programming) in the form of a transaction advice and an AspectJ pointcut to define where the transactions should
be applied

The pointcut applies to any method called on the ProductManager interface. The advice is a transaction advice that applies to methods with a name starting with 'save'.
- using the DBCP connection pool

- add lib spring-aspects & dbcp in dom.xml

- run & enjoy

Click here to download:
springapp.rar (13 KB)

Filed under: java, Spring, web

Quân says...

- Using mySQL 

- Create database startup script
'springapp/db/create_products.sql'

'springapp/db/load_data.sql'

Run scripts and load test data

- Create a Data Access Object (DAO) implementation for JDBC
'springapp/repository/ProductDao.java'

'springapp/repository/JdbcProductDao.java'
+ using Spring's JDBC, don't have to worry about opening and closing
the connection or any statements, won't have to catch any exceptions
+ SimpleJdbcDaoSupport provides SimpleJdbcTemplate

+ getSimpleJdbcTemplate().query: provide the SQL statement and a
class that can handle the mapping between the ResultSet and the
Product class
+ ProductMapper implement ParameterizedRowMapper: mapRow map the
data from each row into a class
+ MapSqlParameterSource allows us to use named parameters instead of
the typical "?"

- Add a private field named 'id' complete with setters and getters to Product.java

- Implement tests for JDBC DAO implementation
Add Spring test framework

JdbcProductDaoTests.java

+ extending AbstractTransactionalDataSourceSpringContextTests --> load application context (test-content.xml)
+ onSetUpInTransaction: clear table & load data test, rolled back once the test finishes
test/resources/test-context.xml

test/resources/jdbc.properties

- Run unit test

Click here to download:
springapp.rar (14 KB)

Filed under: java, jdbc, Spring, web