I has locks..



  • In Java it's too easy to code "working" code, but often this leads to someone shooting itself on the foot... Take persistence for example. It is not a good idea to use the default serialization mechanisms, since they are slow, bloated and whatever.

    So next step, create your complete serialization mechanism, right? It wouldn't be so bad if it were implemented *not* like this:

        public void writeState(ObjectOutputStream oos) throws IOException {

           synchronized (getLock(someMap1)) {
                oos.writeObject(someMap1);
            }

            //...

            synchronized (getLock(someMapn)) {
                oos.writeObject(someMapn);
            }
        }    

    And now we've blown the whole leg."Hey, this class is used by multiple threads!" I guess someone had said.

     

    Not happy at this point, someone must forced a jump on a landmine (with the remaining leg):

        private Object getLock(Object obj){
            if(obj != null){
                return obj;
            }
            return new Object();
        }

    And the icing on the cake? The serialization of the involved class can only happen in a application state where it is single threaded, and the maps are initialized on the constructor...

     


Log in to reply