How can I find the number of live objects on the heap in Java program?
jmap is the standard java utility that you can use to capture heap dumps and statistics. I can't say what protocol is used by jmap to connect to the JVM to get this info, and it's not clear if this information is available to a program running in the JVM directly (though I'm sure the program can query it's JVM through some socket to get this information).
JVM TI is a tool interface used by C code, and it has pretty much full access to the goings on of the JVM, but it is C code and not directly available by the JVM. You could probably write a C lib and then interface with it, but there's nothing out of the box.
There are several JMX MBeans, but I don't think any of them provide an actual object count. You can get memory statistics from these though (these are what JConsole uses). Check out the java.lang.management classes.
If you want some fast (easy to implement, not necessarily a quick result as a jmap takes some time), I'd fork off a run of jmap, and simply read the resulting file.
The simplest way is to use jmap tool. If you will print objects histogram at the end you'll see total number of instances and also accumulated size of all objects:
jmap -histo <PID> will print whole objects with number of instances and size. The last line will contain total number
Total 2802946 174459656
Second column is total instances count, and last is total bytes.
Use jvisualvm, and do a memory sample. It will show the number of classes and instances:
There is a hack you can try:
create your own java.lang.Object (copy the original source)
count the created objects in the constructor (not called for arrays)
add the path to your classfile to the boot classpath
see this (old) article for a sample.
Probably there are better ways to do it using JPDA or JMX, but I've not found how...
As far as I know, you cannot. You can, however, get the amount of memory used for the program:
Runtime rt = Runtime.getRuntime();
System.out.println("Used: " + (rt.totalMemory() - rt.freeMemory());
System.out.println("Free: " + rt.freeMemory());
System.out.println("Total: " + rt.totalMemory());
If all your objects are created using some kind of Factory class you can find number of objects in the heap. Even then you have to have something in the finalize() method. Of course, this cannot be done for all objects, e.g. the jdk library classes cannot be modified. But if you want to find number of instances of a particular class you have created you can potentially find that.
For debugging, you can use a profiler (like YourKit, a commercial java profiler). You'll find both open source and commercial variants of java profilers.
For integration with your code, you might look at using "Aspect Oriented Programming" technique. AOP frameworks (e.g. AspectWerkz) let you change the class files at class load time. This will let you modify constructors to register objects to your "all-my-runtime-objects-framework".
public class NumOfObjects {
static int count=0;
{
count++;
}
public static void main(String[] args)
{
NumOfObjects no1=new NumOfObjects();
System.out.println("no1:" + count);//1
NumOfObjects no2=new NumOfObjects();
System.out.println("no2:"+ count); //2
for (int i=0; i<10;i++)
{
NumOfObjects noi=new NumOfObjects();
}
System.out.println("Total objects:"+count);// 12
}
}
public class ObjectCount
{
static int i;
ObjectCount()
{
System.out.println(++i);
}
public static void main(String args[])
{
ObjectCount oc = new ObjectCount();
ObjectCount od = new ObjectCount();
ObjectCount oe = new ObjectCount();
ObjectCount of = new ObjectCount();
ObjectCount og = new ObjectCount();
}
}
class Test1
{
static int count=0;
public Test1()
{
count++;
System.out.println("Total Objects"+" "+count);
}
}
public class CountTotalNumberOfObjects
{
public static void main(String[] args)
{
Test1 t = new Test1();
Test1 t1 = new Test1();
Test1 t3 = new Test1();
Test1 t11 = new Test1();
Test1 t111 = new Test1();
Test1 t13 = new Test1();
}
}
Related
How can I find the number of live objects on the heap in Java program?
jmap is the standard java utility that you can use to capture heap dumps and statistics. I can't say what protocol is used by jmap to connect to the JVM to get this info, and it's not clear if this information is available to a program running in the JVM directly (though I'm sure the program can query it's JVM through some socket to get this information).
JVM TI is a tool interface used by C code, and it has pretty much full access to the goings on of the JVM, but it is C code and not directly available by the JVM. You could probably write a C lib and then interface with it, but there's nothing out of the box.
There are several JMX MBeans, but I don't think any of them provide an actual object count. You can get memory statistics from these though (these are what JConsole uses). Check out the java.lang.management classes.
If you want some fast (easy to implement, not necessarily a quick result as a jmap takes some time), I'd fork off a run of jmap, and simply read the resulting file.
The simplest way is to use jmap tool. If you will print objects histogram at the end you'll see total number of instances and also accumulated size of all objects:
jmap -histo <PID> will print whole objects with number of instances and size. The last line will contain total number
Total 2802946 174459656
Second column is total instances count, and last is total bytes.
Use jvisualvm, and do a memory sample. It will show the number of classes and instances:
There is a hack you can try:
create your own java.lang.Object (copy the original source)
count the created objects in the constructor (not called for arrays)
add the path to your classfile to the boot classpath
see this (old) article for a sample.
Probably there are better ways to do it using JPDA or JMX, but I've not found how...
As far as I know, you cannot. You can, however, get the amount of memory used for the program:
Runtime rt = Runtime.getRuntime();
System.out.println("Used: " + (rt.totalMemory() - rt.freeMemory());
System.out.println("Free: " + rt.freeMemory());
System.out.println("Total: " + rt.totalMemory());
If all your objects are created using some kind of Factory class you can find number of objects in the heap. Even then you have to have something in the finalize() method. Of course, this cannot be done for all objects, e.g. the jdk library classes cannot be modified. But if you want to find number of instances of a particular class you have created you can potentially find that.
For debugging, you can use a profiler (like YourKit, a commercial java profiler). You'll find both open source and commercial variants of java profilers.
For integration with your code, you might look at using "Aspect Oriented Programming" technique. AOP frameworks (e.g. AspectWerkz) let you change the class files at class load time. This will let you modify constructors to register objects to your "all-my-runtime-objects-framework".
public class NumOfObjects {
static int count=0;
{
count++;
}
public static void main(String[] args)
{
NumOfObjects no1=new NumOfObjects();
System.out.println("no1:" + count);//1
NumOfObjects no2=new NumOfObjects();
System.out.println("no2:"+ count); //2
for (int i=0; i<10;i++)
{
NumOfObjects noi=new NumOfObjects();
}
System.out.println("Total objects:"+count);// 12
}
}
public class ObjectCount
{
static int i;
ObjectCount()
{
System.out.println(++i);
}
public static void main(String args[])
{
ObjectCount oc = new ObjectCount();
ObjectCount od = new ObjectCount();
ObjectCount oe = new ObjectCount();
ObjectCount of = new ObjectCount();
ObjectCount og = new ObjectCount();
}
}
class Test1
{
static int count=0;
public Test1()
{
count++;
System.out.println("Total Objects"+" "+count);
}
}
public class CountTotalNumberOfObjects
{
public static void main(String[] args)
{
Test1 t = new Test1();
Test1 t1 = new Test1();
Test1 t3 = new Test1();
Test1 t11 = new Test1();
Test1 t111 = new Test1();
Test1 t13 = new Test1();
}
}
I have the following piece of code which I want to measure the performance of, both in terms of time and memory usage:
public static void main(String[] args) throws IOException {
final String bigFile = "large-file.txt";
if (args.length == 1) {
List<String> lines = Utils.readLinesFromFile(bigFile);
Path path = Paths.get(bigFile);
if (Files.exists(path)) {
lines = Files.readAllLines(Paths.get(bigFile), StandardCharsets.UTF_8);
}
List<String> filteredLines = lines.stream().filter(x -> x.startsWith(args[0])).collect(Collectors.toList());
for (String s: filteredLines) {
System.out.println(s);
}
} else {
System.out.println(String.format("Expected one argument"));
}
}
where large-file.txt is a file with 2,000,000 lines.
I don't really know how to measure the performance. Should I be using a profiler (can I use a profiler given the program is so short-running?), or would it be adequate to use System.nanoTime() throughout the code and run the program multiple times to get some sort of average performance? This doesn't help in terms of memory usage though - unless I can use Runtime.totalMemory() calls to measure before and after the load of the large file into memory.
You can use Guava stop watch to measure execution time
Stopwatch stopwatch = new Stopwatch().start();
method call();
System.out.println(stopwatch.stop())
I want to call the Groovy scripts from Java and refresh the Groovy scripts periodically.
For example ,
public class AppTest {
public static void main(String args[]) throws Exception {
TestVO test = new TestVO();
AnotherInput input = new AnotherInput();
test.setName("Maruthi");
input.setCity("Newark");
GroovyClassLoader loader = new GroovyClassLoader(AppTest.class.getClassLoader());
Class groovyClass = loader.parseClass(new File("src/main/resources/groovy/MyTestGroovy.groovy"));
GroovyObject groovyObject = (GroovyObject) groovyClass.newInstance();
Object[] inputs = {test,null};
Map<String,String> result = (Map<String, String>)groovyObject.invokeMethod("checkInput", inputs);
System.out.println(result);
}
}
And my Groovy script is
class MyTestGroovy {
def x = "Maruthi";
def checkInput = { TestVO input,AnotherInput city ->
if(input.getName().equals(x)) {
input.setName("Deepan");
println "Name changed Please check the name";
} else {
println "Still Maruthi Rocks";
}
Map<String, String> result = new HashMap<String,String>();
result.put("Status", "Success");
if(city != null && city.getCity().equalsIgnoreCase("Newark")) {
result.put("requested_State", "Newark");
}
return result;
}
def executeTest = {
println("Test Executed");
}
}
How efficient my memory would be managed when I create multiple instances of groovy script and execute the script. Is it advisable to use a number of Groovy scripts as my customized rule engine. Please advise.
It is usually better to have several instances of the same script, than parsing the class every time you want to create an instance. Performance wise that is because compiling the script takes some time, you have to pay in addition to creating an instance. Memory wise you use up the number of available classes up faster. Even if old classes are collected, if you have many scripts active, it can happen... though that normally means hundreds or even thousands of them (depends on the jvm version and your memory settings)
Of course, once the script changed, you will have to recompile the class anyway. So if in your scenario you will have only one instance of the class active at the same time, and a new instance is only required after a change to the source, you can recompile every time.
I mention that especially, because you might even be able to write the script in a way, that let's you reuse the same instance. But it is of course beyond the scope of this question.
Just a question from a noob: how do I avoid huge main (in case of JavaFX, start) methods? I tend to create one-class projects but I know that's incorrect. Basically I do not know when to create dedicated classes for specific tasks.
I hope this question is not so stupid.
It's a not a stupid question. From what you've said, you might not need other classes. You may just need methods.
Lets look at a simple example:
public class MyClass {
public static void main(String[] args) {
int i = 4 + 2;
System.out.println(4 + 2);
}
}
Easy, right? But now, what if it gets harder.
public class MyClass {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
int k = i + (7 / 2) * 3 / 14;
System.out.println(i + " " + k);
}
}
}
Now obviously, this isn't actually harder. But notice how there is a pattern? We take every number 0-9, and add (7 / 2) * 3 / 14. This can be moved into a method:
int getNumber(int i) {
return i + (7 / 2) * 3 / 14);
}
Now, our code looks much cleaner, as we don't have to deal with any addition or division or multiplication
public class MyClass {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
int k = getNumber(i);
System.out.println(i + " " + k);
}
}
}
This example might seem dumb, because it involves a very easy math problem, but the point is: If you have something that you do repeatedly, put it in a method.
Note:
Methods can also be used to split up a large function. When in doubt, divide and conquer!
See this:
void run() {
getInput();
tick();
render();
}
Is much cleaner than something like this:
void run() {
Scanner reader = new Scanner(System.in);
System.out.println("Enter a number: ");
String string = reader.nextString();
MyObject obj = new MyObject();
obj.doSomething(string);
obj.render();
}
If you looked at that code you'd have no idea what it was doing! But the first example you would, because it divides into methods that clearly identify what they do.
Anyway, about classes:
Google OOP! There are tons of great resources. For most classes, you can think of them as a container. You could create a class, Wallet, that would contain Coins and manipulate it (think spend, remove, add).
There is no stupid question :)
You ask about Oriented Object Programming concept.
In Java, C++ or Php Object, the purpose is to store your code into logical aera. Immagine your code like life. Immagine everything act like an object.
For example, your program is simulating car.
In your code you will have an class Car, then a class Engine, then class BMW that inherit from Car and Car who is containing a instance of Engine.
In internet (use google) you will find a lots of explanation about how OOP work. All of this will explain this much better than i will.
If you have any question, you are welcome :)
This is my opinion that I've developed over the course of learning to program. Though my background is moreso with perl scripting and not oop
Separate the presentation from the data/logic.
Meaning, everything should be in classes (or function), and from the main thread you merely pass the object (or function) data, and you get data the same way.
If it does a specific set of tasks, make a class out of it.
If it could be used for other purposes make a class out of it.
If it does a specific operation, make a function out of it.
Does anyone know how can I create a new Performance Counter (perfmon tool) in Java?
For example: a new performance counter for monitoring the number / duration of user actions.
I created such performance counters in C# and it was quite easy, however I couldn’t find anything helpful for creating it in Java…
If you want to develop your performance counter independently from the main code, you should look at aspect programming (AspectJ, Javassist).
You'll can plug your performance counter on the method(s) you want without modifying the main code.
Java does not immediately work with perfmon (but you should see DTrace under Solaris).
Please see this question for suggestions: Java app performance counters viewed in Perfmon
Not sure what you are expecting this tool to do but I would create some data structures to record these times and counts like
class UserActionStats {
int count;
long durationMS;
long start = 0;
public void startAction() {
start = System.currentTimeMillis();
}
public void endAction() {
durationMS += System.currentTimeMillis() - start;
count++;
}
}
A collection for these could look like
private static final Map<String, UserActionStats> map =
new HashMap<String, UserActionStats>();
public static UserActionStats forUser(String userName) {
synchronized(map) {
UserActionStats uas = map.get(userName);
if (uas == null)
map.put(userName, uas = new UserActionStats());
return uas;
}
}