Skip to content

Instantly share code, notes, and snippets.

@mambax
Created July 24, 2015 08:11
Show Gist options
  • Save mambax/8148f896b04492f4b5fc to your computer and use it in GitHub Desktop.
Save mambax/8148f896b04492f4b5fc to your computer and use it in GitHub Desktop.
public class GraphGymnastic extends Application {
final ExecutorService serv = Executors.newFixedThreadPool(2);
public static void main(String argv[]) {
launch(argv);
}
@Override public void start(Stage primaryStage) throws Exception {
//Setup UI
primaryStage.setTitle("Demo");
final List<Node> nodesInGraph = new ArrayList<>();
final FlowPane p = new FlowPane() {{
setId("flowpane");
getChildren().addAll(new Label("Label") {{
setId("label");
}}, new Button("Button") {{
setId("button");
// setOnMouseClicked(event -> handle(event, nodesInGraph)); //Uncomment and comment below to see effects!
setOnMouseClicked(event -> handleAsync(event, nodesInGraph));
}});
setHgap(5);
}};
//Assume that this goes recursive and deep into a scene graph but still
// returns a list
//Here it takes the two childs for simplicity
nodesInGraph.addAll(p.getChildrenUnmodifiable());
//Show stage
primaryStage.setScene(new Scene(p));
primaryStage.show();
}
public void handle(MouseEvent ev, List<Node> nodesInGraph) {
if (null != nodesInGraph)
Platform.runLater(() -> nodesInGraph.forEach(node -> {
//This will block the UI thread, so there is the need for a second
//thread
System.out.println(
"Calculating heavy on node " + node.toString() + " with event from "
+ ev.getSource().toString());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}));
}
public void handleAsync(MouseEvent ev, List<Node> nodesInGraph) {
if (null != nodesInGraph)
serv.submit(() -> nodesInGraph.forEach(node -> {
//Now there is a second thread but it works on a LIVE view object
// list, which is ugly
//Option 1: Keep it like this, drawbacks? :S
//Option 2: Copy the graph, costs performance... How deep should it
// copy? :S
System.out.println(
"Calculating heavy on node " + node.toString() + " with event from "
+ ev.getSource().toString());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment