//package memoryleak; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Iterator; import java.util.concurrent.atomic.AtomicLong; import javafx.animation.AnimationTimer; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.scene.control.TabPane.TabClosingPolicy; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.stage.Stage; public class TabMemoryLeak extends Application { public static void main(final String... args) { Application.launch(args); } @Override public void start(final Stage stage) throws Exception { final BorderPane root = new BorderPane(); final TabPane tabs = new TabPane(); tabs.setTabClosingPolicy(TabClosingPolicy.ALL_TABS); root.setCenter(tabs); final HBox line = new HBox(4); createButtons(line, tabs); root.setTop(line); stage.setScene(new Scene(root, 500, 500)); stage.show(); } private void createButtons(final HBox line, final TabPane tabs) { final Button addTab = new Button("add Tab"); addTab.setOnAction(e -> tabs.getTabs().add(new MyTab())); line.getChildren().add(addTab); final Button clearTabs = new Button("clear Tabs"); clearTabs.setOnAction(e -> tabs.getTabs().clear()); line.getChildren().add(clearTabs); // call GC final Button gc = new Button("GC"); gc.setOnAction(e -> System.gc()); line.getChildren().add(gc); // show tab count final Label countTab = new Label(); line.getChildren().addAll(countTab); AnimationTimer timer = new AnimationTimer() { @Override public void handle(long now) { countTab.setText("Tabs: " + MyTab.getCount()); } }; timer.start(); } static class MyTab extends Tab { private static final ArrayList> allTabs = new ArrayList<>(); protected static final AtomicLong ID = new AtomicLong(0); private final long id; MyTab() { super(); this.id = ID.getAndIncrement(); setText("Tab " + this.id); setId("Tab " + this.id); allTabs.add(new WeakReference<>(this)); } static int getCount() { int count = 0; Iterator> it = allTabs.iterator(); while (it.hasNext()) { if (it.next().get() != null) { count++; } else { it.remove(); } } return count; } } }