• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
  • paul wheaton
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Henry Wong
Saloon Keepers:
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Tim Moores
  • Mikalai Zaikin
Bartenders:
  • Frits Walraven

Finding out current memory usage

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
Does anyone know what class can be used to print the current memory usage?
I looked into class System, but couldn't find any specific method for that purpose.
Thanks.
Bon
 
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Bon,
Welcome to JavaRanch. You can't find it because it isn't there. The JVM takes care of all memory management for you, so why do you need to know this?
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Well, it depends what you want. Java does provide
System.getRuntime().totalMemory()
and

System.getRuntime().freeMemory()
which refer to the amount of JVM heap space currently allocated, and currently allocated but unused, respectively. But this is only part of the total memory picture, and can give misleading results. E.g. when freeMemory() goes to zero, the system may simply allocate more memory to the JVM (if you're not already at the limit set by the -mx option) and suddenly the numbers change. And these numbers may not include all memory associated with your Java process. For example many java.nio classes allow you to interact with memory outside the JVM, like for a memory-mapped file. (No, you can't access just any memory, but specially allocated memory that's nonetheless outside the JVM).
Generally, if you want more info on how much memory you're using, you probably need to ask the operating system, not Java.
 
Bon Truong
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Well, I have written a class that performs object pooling. Then I write a JUnit program that tests object pooling in order to provide some data which would hopefully justify the usage of object pooling.
Thanks to all for your feedback.
Bon
 
Bon Truong
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
By the way, it's "Runtime.getRuntime().freeMemory()" and not "System.getRuntime().freeMemory()".

Thanks.
Bon
 
Ranch Hand
Posts: 155
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
HI! Everyone,
I too wrote small program which used freememory() and Totalmemory(). I needed this program as I was getting java.outofmemoryerror very frequently. But this program dosen't tell you much . Because I ran this program after getting this error and after restarting TOMCAT/APACHE but numbers were same.

SA
 
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
GENERATING DIAGNOSTICS BY MONITORING THE SYSTEM EVENT QUEUE
Have you ever wanted your applications to have a "hot key" for system diagnostics? You could then press the key (using a key sequence like CTRL-ALT-Z), to generate system diagnostic information. And you could use the key to generate diagnostics from anywhere in the application. You could create the function theoretically by registering a KeyListener with every component in your application space. However, the Java platform provides a simpler approach: you can implement the AWTEventListener interface, and attach it to the system event queue. This tip illustrates this simpler approach.
First, a word of caution is advised. Attaching a listener to the system event queue will slow down your application's operations. Every event sourced from a Component or MenuComponent is checked against your listener. Using this feature should be reserved for special cases such as automated testing, working with accessibility features, and other cases where the exact timing of operations can be affected without altering system behavior. Secondly, as with all event-handling operations, if the task you want to perform is not very quick, you should create a secondary thread to perform the operation. This is especially true when monitoring the system event queue with an AWTEventListener -- that's because as any blocking operations will seriously degrade the performance of your application.
With that cautionary note, let's examine AWTEventListener. The interface itself is just a single method:
public void eventDispatched(AWTEvent event)
Once registered, an AWTEventListener implementation is notified when the events you are interested in happen. The "events you are interested in" are identified as part of the registration process. Then, after you perform your special operation, the system passes the event to its appropriate location.
You register an AWTEventListener by using the addAWTEventListener method of Toolkit (Toolkit is the abstract superclass of Abstract Window Toolkit implementations). The method signature looks like this:
void addAWTEventListener(AWTEventListener listener,
long eventMask)
The eventMask parameter requires some explanation. Instead of responding to all events, an AWTEventListener is typically interested in only a specific subset of them, such as focus or key events. When setting an eventMask, you identify the event types of interest. This limits the amount of processing passes through the listener code. The AWTEvent class defines a series of constants, such as FOCUS_EVENT_MASK, MOUSE_EVENT_MASK, and KEY_EVENT_MASK. These are the masks that represent the types of events that can go through the event queue. You specify a mask for each type of event you want checked, and you combine them in a single variable to get the masks to pass into the registration call. So, if you want to create a listener to monitor the different focus events, you combine FOCUS_EVENT_MASK, for the component-oriented focus events, with WINDOW_FOCUS_EVENT_MASK, for the window-oriented events. You combine the masks using the OR ( | ) operator, as shown here:
long mask =
FOCUS_EVENT_MASK | WINDOW_FOCUS_EVENT_MASK;
After you combine the masks, you attach them to the Toolkit:
AWTEventListener listener = ...;
Toolkit toolkit = Toolkit.getDefaultToolkit();
toolkit.addAWTEventListener(listener, mask);
At that point, your program is watching for the masked events -- in this case, component-oriented focus events and window-oriented events.
Here's an example. The following program displays two screens (one on top of the other), each with its own text field. The "monitoring" task records every key typed into either frame's text field. When either frame is closed, the recorded keystrokes are displayed to the console.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Monitor {
static StringBuffer buffer =
new StringBuffer(100);
static class TextFrame extends JFrame {
TextFrame() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container pane = getContentPane();
JTextField tf = new JTextField();
pane.add(tf, BorderLayout.NORTH);
setSize(100, 50);
show();
WindowListener listener =
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
done();
}
};
addWindowListener(listener);
}
}
public static void done() {
if (buffer.length() > 0) {
System.out.println(buffer.toString());
buffer.setLength(0);
}
}
public static void main(String args[]) {
AWTEventListener listener =
new AWTEventListener() {
public void eventDispatched(AWTEvent event) {
KeyEvent ke = (KeyEvent)event;
if (ke.getID() == KeyEvent.KEY_TYPED) {
buffer.append(ke.getKeyChar());
}
}
};
Toolkit toolkit = Toolkit.getDefaultToolkit();
toolkit.addAWTEventListener(
listener, AWTEvent.KEY_EVENT_MASK);
new TextFrame();
new TextFrame();
}
}
One aspect of the program is worth mentioning. Because the buffer variable is only accessed from the system event thread (within eventDispatched specifically), access to the variable does not need to be synchronized. If the variable was accessed from outside the event thread, in addition to inside, the variable would need to be synchronized.
Here's a second example. The following program demonstrates how to watch for a special key sequence: in this case, CTRL-ALT-Z. In a program like this, the eventDispatched method can be called frequently, so it's important to minimize the creation of objects within the listener. Otherwise, the garbage collector will be kept quite busy freeing the objects created for each pass. Much of the program is the same as for the first example. The major changes relate to actions taken in response to the triggering event (pressing CTRL-ALT-Z). Instead of capturing keystrokes, the program reports the amount of free memory in the Java virtual machine*.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GetMem {
static class TextFrame extends JFrame {
TextFrame() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container pane = getContentPane();
JTextField tf = new JTextField();
pane.add(tf, BorderLayout.NORTH);
setSize(100, 50);
show();
}
}
public static void main(String args[]) {
AWTEventListener listener =
new AWTEventListener() {
int keyId = KeyEvent.KEY_PRESSED;
int keyCode = KeyEvent.VK_Z;
int keyModifiers =
(InputEvent.CTRL_MASK | InputEvent.ALT_MASK);
public void eventDispatched(AWTEvent event) {
KeyEvent ke = (KeyEvent)event;
if ((ke.getID() == keyId) &&
(ke.getKeyCode() == keyCode) &&
(ke.getModifiers() == keyModifiers)) {
System.out.println(
Runtime.getRuntime().freeMemory());
}
}
};
Toolkit toolkit = Toolkit.getDefaultToolkit();
toolkit.addAWTEventListener(
listener, AWTEvent.KEY_EVENT_MASK);
new TextFrame();
new TextFrame();
}
}
The activate key combination you select must be sensitive to platform and application-specific options. Be sure to select a combination that is unique.
Obviously, much more complicated operations could happen in response to the triggering sequence. However, no matter what the actions are, the way you create and register the sequence is the same:
Create the AWTEventListener
Determine the appropriate mask
Register the listener with the Toolkit
When you use an AWTEventListener, you typically assign the sequence to the event queue for the life of the application. However to monitor a situation, it might be necessary to only temporarily associate the listener with the queue. In this case, remember to remove the listener, with the removeAWTEventListener method of Toolkit, when the monitoring operation completes.
For more information on ways to debug an AWT application, including using AWTEventListener, see Chapter 7 of Advanced Programming for the Java 2 Platform.
 
Do not meddle in the affairs of dragons - for you are crunchy and good with ketchup. Crunchy tiny ad:
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic