Testing memory leaks with creation of multiple @Dependent instances with WildFly 18.0.1
@Dependent
public class Book {
@Inject
protected GlobalService globalService;
protected byte[] data;
protected String id;
public Book() {
}
public Book(GlobalService globalService) {
this.globalService = globalService;
init();
}
@PostConstruct
public void init() {
this.data = new byte[1024];
Arrays.fill(data, (byte) 7);
this.id = globalService.getId();
}
}
@ApplicationScoped
public class GlobalFactory {
@Inject
protected GlobalService globalService;
@Inject
private Instance<Book> bookInstance;
public Book createBook() {
return bookInstance.get();
}
public Book createBook2() {
Book b = bookInstance.get()
bookInstance.destroy(b);
return b;
}
public Book createBook3() {
return new Book(globalService);
}
}
@Singleton
@Startup
@ConcurrencyManagement(value = ConcurrencyManagementType.BEAN)
public class GlobalSingleton {
protected static final int ADD_COUNT = 8192;
protected static final AtomicLong counter = new AtomicLong(0);
@Inject
protected GlobalFactory books;
@Schedule(second = "*/1", minute = "*", hour = "*", persistent = false)
public void schedule() {
for (int i = 0; i < ADD_COUNT; i++) {
books.createBook();
}
counter.addAndGet(ADD_COUNT);
System.out.println("Total created: " + counter);
}
}
After creating 200k of Book I get the OutOfMemoryError. It's clear to me because it is written here
CDI Application and Dependent scopes can conspire to impact garbage collection?
But I have another questions:
Why OutOfMemoryError occurred only if GlobalService in Book is stateless EJB, but not if @ApplicationScoped. I thought that @ApplicationScoped for GlobalFactory is enough to get OutOfMemoryError.
What method better createBook2() or createBook3()? Both remove problem with OutOfMemoryError
- Is there other variant of createBook()?