The call to optimize() should not be part of any method. Instead, it must be called afterwards after rebuildIndex() of the top level class finished.