Reassigning the outer class reference

Everyone knows (or should) that a non-static inner classe has a hidden reference to the instance of its containing class.

Let's exercise this sample class :

public class Outer {
 
    private final int i;
 
    public Outer(int i) {
        this.i = i;
    }
 
    public class Inner {
        public void print() {
            System.out.println(i);
        }
    }
 
}
Lire la suite...

Filesystem notifications with Java 7

A developer sought yesterday some advice about the best way to implement the following feature in his application : how to react, as quickly as possible, to the creation of a special "lock file" in a well-known directory.
His current implementation uses a polling thread calling the File.exists() method every few hundreds ms, which is a best-effort tradeoff between notification speed and unnecessary CPU burning.

As of Java 7, there is a better way to achieve this.
The java.nio.file package provides a WatchService that plugs directly into the underlying OS's file notification system, allowing the application to be asychronously notified of filesystem-related events of certain types (file creation, modification, deletion, etc.).

This WatchService works alot like the dreaded NIO channel Selector, but is fortunately simpler : first declare which events you are interested in, then loop on a blocking method to wait for some event to occur, process it as required, rince and repeat.

Here is what I quickly coded as a proof-of-concept.

Lire la suite...

Serialization and magic methods

As I explained in my last article, Java's serialization mechanism is very powerful and flexible.
When an instance gets serialized, ObjectOutputStream looks for a handful of "magic methods" that the developer can provide to customize the process. In this short article, we'll see what they are, what they do and in which order they are called in the serialization pipeline.

Lire la suite...

Sérialiser des objets non sérialisables

Le mécanisme de sérialisation de Java permet de compresser un graphe d'objets sous une forme compacte, transportable hors de la JVM, puis de reconstituer ces objets en mémoire - à condition qu'ils implementent Serializable.

Dans cet article, je vous propose de découvrir et de tirer parti de certaines options méconnues pour sérialiser des objets n'implémentant pas Serializable - et sans même les modifier !

Lire la suite...

Java WTF #1 : List.toArray()

Pour transformer une Liste en tableau, la méthode habituelle consiste à utiliser List.toArray(), héritée de l'interface Collection. Cette méthode possède deux variantes :

  • Une simple, qui renvoie un tableau d'Object que vous devez ensuite caster dans le bon type ;
  • Une plus complexe, qui prend en paramètre un tableau du type désiré et le remplit avec les valeurs de la liste. Elle est généralement préférée, parce qu'elle permet éventuellement de recycler un tableau existant, et surtout parce qu'elle évite le cast.
public Object[] toArray()
public <T> T[] toArray(T[] a)

Mais examinons de plus près la Javadoc de la seconde méthode...

Lire la suite...