Java process physical memory increases continuously - memory

I've run into a situation where a simple canvas
Drawing app shows a gradual increase in physical
Memory usage over time until it hits about 80% mark
And tries to maintain the process memory usage around
That number (that is the %MEM column when 'top' is run, 64bit Linux box). Of course by that point page swapping kicks in. I've tried to limit memory usage by using -Xmx10m -Xms10m and even -XX:+UseG1GC but nothing appears to make a difference.
Just a side note, I've even tried the StockLineChartApp example shipped with oracle jdk Javafx examples and it displays a physical memory usage increase as well. I'm using jdk1.8.0_102.
Any feedback regarding this issue would be very helpful. Thanks.
//
package test8;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import javafx.util.Duration;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.animation.Animation;
public class Test8 extends Application {
GraphicsContext gc;
double x;
double y;
#Override
public void start(Stage primaryStage) {
try {
Group root = new Group();
Scene s = new Scene(root, 600, 400, Color.BLACK);
final Canvas canvas = new Canvas(500,300);
gc = canvas.getGraphicsContext2D();
root.getChildren().add(canvas);
Pane pane = new Pane();
pane.getChildren().add(root);
Scene scene = new Scene(pane);
primaryStage.setTitle("canvas test");
primaryStage.setScene(scene);
primaryStage.show();
gc.beginPath();
x = 0.0;
y = 0.0;
EventHandler onFinished = new EventHandler<ActionEvent>() {
public void handle(ActionEvent t) {
y = (y<canvas.getHeight()) ? (y + 10.0) : 0.0;
x = (x<canvas.getWidth()) ? (x + 5.0) : 0.0;
gc.lineTo(x,y);
gc.stroke();
if (x==0.0) gc.beginPath();
}
};
final Timeline timeline = new Timeline();
timeline.setCycleCount(Animation.INDEFINITE);
timeline.setAutoReverse(true);
timeline.getKeyFrames().add(new KeyFrame(Duration.millis(40), onFinished));
timeline.play();
} catch (Exception e) {
System.out.println("Application start Exception");
} finally {
}
}
public static void main(String[] args) {
launch(args);
}
}

Related

How to convert PlanarImage or BufferedImage (JAI) to Image (JavaFX)

I am trying to change the image represented in an ImageView instance, after manipulating it with JAI. JAI can output a PlanarImage, RenderedImage(non-awt), or BufferedImage(non-awt), but these are not valid types for ImageView construction.
import java.awt.image.renderable.ParameterBlock;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.image.ImageView;
import javafx.scene.image.Image;
import javafx.stage.Stage;
import javax.media.jai.JAI;
import javax.media.jai.PlanarImage;
import javax.media.jai.Interpolation;
public class A11 extends Application{
int zoom = 100;
ImageView img = new ImageView();
Image src = new Image("file.bmp");
public static void main(String args[]){
launch(args); // start application
}
#Override
public void start(Stage window){
ParameterBlock pb = new ParameterBlock();
pb.addSource(src); // source Image
pb.add(zoom/100); // xScale
pb.add(zoom/100); // yScale
pb.add(0.0F); // xTranslate
pb.add(0.0F); // yTranslate
pb.add(Interpolation.getInstance(Interpolation.INTERP_BICUBIC));
PlanarImage dest = JAI.create("scale", pb, null);
// NEED TO CONVERT 'dest' TO 'destImage' HERE
ImageView frame = new ImageView(destImage);
ScrollPane pane = new ScrollPane(frame);
window.setScene(new Scene(pane,800,600));
window.show();
}
}

JavaFx OnError MediaView Memory leak

I have software that I am working on that uses JavaFx MediaPlayers and MediaViews to create a UI. For this to work the way we want we are reusing the MediaPlayers (after keeping them stored in a static class's hashMap) and then we place the MediaPlayer in new MediaViews when needed. When the MediaView is done we set it to null and move on, but this has lead to a memory leak where the number of players will stay constant but the mediaViews will increase. I made a minimal working version of this code so you can see the memory go up and up without collecting any mediaViews. It seems like the getOnError or the Error property from the MediaPlayer is holding onto an old reference of the MediaView. I would like to remove this, but it seems like you have to dispose of a mediaPlayer if you want to clean up all of it's memory, but I would like to save the Player and delete the View.
Here is some code that recreates the issue. Just hit the stop button a few times which will remove the old mediaView and add a new one, but none ever get cleaned up.
package JavaFx;
import java.io.File;
import java.net.URL;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.effect.DropShadow;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaPlayer.Status;
import javafx.scene.media.MediaView;
import javafx.stage.Stage;
import javafx.scene.paint.Color;
public class FxMediaExample1 extends Application
{
public static void main(String[] args)
{
Application.launch(args);
}
public MediaView mediaView;
public Scene scene;
public VBox root;
#Override
public void start(Stage stage)
{
// Locate the media content in the CLASSPATH
// Create a Media
File file = new File("file:///C:/Users/Samuel%20Johnston/Downloads/cf86c6a4-271f-4dcb-bb11-fc30f5eb6b45_web.mp4");
if (file.exists()) {
System.out.println("Boobs");
} else {
System.out.println("poop");
}
Media media = new Media("file:///C:/Users/Samuel%20Johnston/Downloads/cf86c6a4-271f-4dcb-bb11-fc30f5eb6b45_web.mp4");
media.setOnError(() -> {
System.out.println("WHAT THE WHAT, " + media.getError().toString());
System.out.println("WHAT THE WHAT, " + media.getError().getMessage());
System.out.println("WHAT THE WHAT, " + media.getError().getStackTrace().toString());
System.out.println("WHAT THE WHAT, " + media.getError().getLocalizedMessage());
});
// Create a Media Player
final MediaPlayer player = new MediaPlayer(media);
player.setOnError(() -> {
System.out.println("WHY THE WHY, " + player.getError().toString());
System.out.println("WHY THE WHY, " + player.getError().getMessage());
System.out.println("WHY THE WHY, " + player.getError().getStackTrace().toString());
System.out.println("WHY THE WHY, " + player.getError().getLocalizedMessage());
});
// Automatically begin the playback
player.setAutoPlay(true);
// Create a 400X300 MediaView
mediaView = new MediaView(player);
mediaView.setFitWidth(700);
mediaView.setFitHeight(700);
mediaView.setSmooth(true);
// Create the Buttons
Button playButton = new Button("Play");
Button stopButton = new Button("Stop");
// Create the Event Handlers for the Button
playButton.setOnAction(new EventHandler <ActionEvent>()
{
public void handle(ActionEvent event)
{
if (player.getStatus() == Status.PLAYING)
{
player.stop();
player.play();
}
else
{
player.play();
}
}
});
stopButton.setOnAction(new EventHandler <ActionEvent>()
{
public void handle(ActionEvent event)
{
player.stop();
root.getChildren().remove(mediaView);
mediaView = new MediaView(player);
mediaView.setFitWidth(700);
mediaView.setFitHeight(700);
mediaView.setSmooth(true);
root.getChildren().add(mediaView);
}
});
// Create the HBox
HBox controlBox = new HBox(5, playButton, stopButton);
// Create the VBox
root = new VBox(5,mediaView,controlBox);
// Set the Style-properties of the HBox
root.setStyle("-fx-padding: 10;" +
"-fx-border-style: solid inside;" +
"-fx-border-width: 2;" +
"-fx-border-insets: 5;" +
"-fx-border-radius: 5;" +
"-fx-border-color: blue;");
// Create the Scene
scene = new Scene(root);
// Add the scene to the Stage
stage.setScene(scene);
// Set the title of the Stage
stage.setTitle("A simple Media Example");
// Display the Stage
stage.show();
}
}

JavaFX2: Webview: Page shows empty screen

I tried displaying the google web page on my javafx view using webview. All it does is display an empty page. For testing I did add a text element at the bottom and it did show up. Any pointers would be helpful. My code and the sample screen are attached.
I am running this application on a Windows 7 machine with 8 GB RAM and this is deployed in an environment that needs proxy authentication.
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
public class MyBrowser extends Application
{
private Pane root;
#Override
public void start(final Stage stage) throws URISyntaxException
{
root = new VBox();
List<Proxy> proxies = ProxySelector.getDefault().select(new URI("http://www.google.com"));
final Proxy proxy = proxies.get(0); // ignoring multiple proxies to simplify code snippet
if (proxy.type() != Proxy.Type.DIRECT)
{
// you can change that to dialog using separate Stage
final TextField login = new TextField("login");
final PasswordField pwd = new PasswordField();
Button btn = new Button("Login");
btn.setOnAction(new EventHandler<ActionEvent>()
{
public void handle(ActionEvent t)
{
System.setProperty("http.proxyUser", login.getText());
System.setProperty("http.proxyPassword", pwd.getText());
displayWebView();
}
});
root.getChildren().addAll(login, pwd, btn);
}
else
{
displayWebView();
}
stage.setScene(new Scene(root, 400, 600));
stage.show();
}
private void displayWebView()
{
root.getChildren().clear();
WebView webView = new WebView();
final WebEngine webEngine = webView.getEngine();
root.getChildren().addAll(webView, new Text("HELLO"));
webEngine.load("http://www.google.com");
}
public static void main(String[] args)
{
launch();
}
}
I copied and pasted your code and ran it on Windows 7 with Java7u40 both Java8b108.
In both cases the code functioned correctly and displayed the http://www.google.com page.
The proxy selector code in your source was not triggered for me (probably because I have a Proxy.Type.DIRECT connection, so there was nothing for it to do).

Run JesterRecommenderEvaluationRunner, but get no results of evaluation

I downloaded the Jester example code in Mahout, and tries to run it on jester dataset to see the evaluation results. the running is done successfully, but the console only has the results:
log4j:WARN No appenders could be found for logger (org.apache.mahout.cf.taste.impl.model.file.FileDataModel).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
I expect to see the evaluation score range from 0 to 10. any one can help me found out how to get the score?
I am using mahout-core-0.6.jar and the following is the code:
JesterDataModel.java:
package Jester;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.regex.Pattern;
import com.google.common.collect.Lists;
import org.apache.mahout.cf.taste.example.grouplens.GroupLensDataModel;
import org.apache.mahout.cf.taste.impl.common.FastByIDMap;
import org.apache.mahout.cf.taste.impl.model.GenericDataModel;
import org.apache.mahout.cf.taste.impl.model.GenericPreference;
import org.apache.mahout.cf.taste.impl.model.file.FileDataModel;
import org.apache.mahout.cf.taste.model.DataModel;
import org.apache.mahout.cf.taste.model.Preference;
import org.apache.mahout.common.iterator.FileLineIterator;
//import org.apache.mahout.cf.taste.impl.common.FileLineIterable;
public final class JesterDataModel extends FileDataModel {
private static final Pattern COMMA_PATTERN = Pattern.compile(",");
private long userBeingRead;
public JesterDataModel() throws IOException {
this(GroupLensDataModel.readResourceToTempFile("\\jester-data-1.csv"));
}
public JesterDataModel(File ratingsFile) throws IOException {
super(ratingsFile);
}
#Override
public void reload() {
userBeingRead = 0;
super.reload();
}
#Override
protected DataModel buildModel() throws IOException {
FastByIDMap<Collection<Preference>> data = new FastByIDMap<Collection<Preference>> ();
FileLineIterator iterator = new FileLineIterator(getDataFile(), false);
FastByIDMap<FastByIDMap<Long>> timestamps = new FastByIDMap<FastByIDMap<Long>>();
processFile(iterator, data, timestamps, false);
return new GenericDataModel(GenericDataModel.toDataMap(data, true));
}
#Override
protected void processLine(String line,
FastByIDMap<?> rawData,
FastByIDMap<FastByIDMap<Long>> timestamps,
boolean fromPriorData) {
FastByIDMap<Collection<Preference>> data = (FastByIDMap<Collection<Preference>>) rawData;
String[] jokePrefs = COMMA_PATTERN.split(line);
int count = Integer.parseInt(jokePrefs[0]);
Collection<Preference> prefs = Lists.newArrayListWithCapacity(count);
for (int itemID = 1; itemID < jokePrefs.length; itemID++) { // yes skip first one, just a count
String jokePref = jokePrefs[itemID];
if (!"99".equals(jokePref)) {
float jokePrefValue = Float.parseFloat(jokePref);
prefs.add(new GenericPreference(userBeingRead, itemID, jokePrefValue));
}
}
data.put(userBeingRead, prefs);
userBeingRead++;
}
}
JesterRecommenderEvaluatorRunner.java
package Jester;
import org.apache.mahout.cf.taste.common.TasteException;
import org.apache.mahout.cf.taste.eval.RecommenderEvaluator;
import org.apache.mahout.cf.taste.impl.eval.AverageAbsoluteDifferenceRecommenderEvaluator;
import org.apache.mahout.cf.taste.model.DataModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
public final class JesterRecommenderEvaluatorRunner {
private static final Logger log = LoggerFactory.getLogger(JesterRecommenderEvaluatorRunner.class);
private JesterRecommenderEvaluatorRunner() {
// do nothing
}
public static void main(String... args) throws IOException, TasteException {
RecommenderEvaluator evaluator = new AverageAbsoluteDifferenceRecommenderEvaluator();
DataModel model = new JesterDataModel();
double evaluation = evaluator.evaluate(new JesterRecommenderBuilder(),
null,
model,
0.9,
1.0);
log.info(String.valueOf(evaluation));
}
}
Mahout 0.7 is old, and 0.6 is very old. Use at least 0.7, or better, later from SVN.
I think the problem is exactly what you identified: you don't have any slf4j bindings in your classpath. If you use the ".job" files in Mahout you will have all dependencies packages. Then you will actually see output.

How to make an overlay on top of JavaFX 2 webview?

Is it possible to to overlay any JavaFx2 widgets or canvas on top of a JavaFX 2 webview?
I want to generate a transparent heatmap by means of JavaFX 2 on top of a webview.
Adding overlay is very easy: just put webview and any pane to StackPane.
Another story is to synchronize overlay and webview data. To achieve that you need to ask webview for object coordinates through javascript. Here is an example which finds stackoverflow question area and marks it on overlay:
public class WebOverlay extends Application {
#Override
public void start(Stage stage) {
StackPane root = new StackPane();
WebView webView = new WebView();
final WebEngine webEngine = webView.getEngine();
Canvas overlay = new Canvas(600,600);
overlay.setOpacity(0.5);
final GraphicsContext gc = overlay.getGraphicsContext2D();
gc.setFill(Color.RED);
root.getChildren().addAll(webView, overlay);
stage.setScene(new Scene(root, 600, 600));
webEngine.getLoadWorker().workDoneProperty().addListener((observable, oldValue, newValue) -> {
if (newValue.intValue() == 100) {
// find coordinates by javascript call
JSObject bounds = (JSObject)webEngine.executeScript("document.getElementsByClassName('question-hyperlink')[0].getBoundingClientRect()");
Number right = (Number)bounds.getMember("right");
Number top = (Number)bounds.getMember("top");
Number bottom = (Number)bounds.getMember("bottom");
Number left = (Number)bounds.getMember("left");
// paint on overlaing canvas
gc.rect(left.doubleValue(), top.doubleValue(), right.doubleValue(), bottom.doubleValue());
gc.fill();
}
});
webEngine.load("http://stackoverflow.com/questions/10894903/how-to-make-an-overlay-on-top-of-javafx-2-webview");
stage.show();
}
public static void main(String[] args) { launch(); }
}
Do you mean something like this:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.RectangleBuilder;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.scene.text.TextBuilder;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
public class Demo extends Application {
#Override
public void start(Stage primaryStage) {
WebView webView = new WebView();
webView.getEngine().load("http://www.google.com");
StackPane root = new StackPane();
root.getChildren().addAll(webView, getOverlay());
primaryStage.setScene(new Scene(root, 300, 250));
primaryStage.show();
}
private Pane getOverlay() {
StackPane p = new StackPane();
Rectangle r = RectangleBuilder.create()
.height(100).width(100)
.arcHeight(40).arcWidth(40)
.stroke(Color.RED)
.fill(Color.web("red", 0.1))
.build();
Text txt=TextBuilder.create().text("Overlay")
.font(Font.font("Arial", FontWeight.BOLD, 18))
.fill(Color.BLUE)
.build();
p.getChildren().addAll(r, txt);
return p;
}
public static void main(String[] args) {
launch(args);
}
}

Resources