Improve the intensity efficiency of Java programs

xiaoxiao2021-03-06  85

Improve the intensity efficiency of Java programs

Original: Forget ideal

2004-11-1

We all know that the Java program is favored by the majority of programmers, because Java has GC (garbage collection), without spending a lot of effort to solve memory release and leak problems. These problems are always C / C programmers need to spend great effort to face seriously.

The problem is always double-sided, GC has brought us great happiness, released a lot of effort and time, but will bring us some small troubles at some point. The Object in Java is not handed over to GC to release it. He is worry-free, following the Memory Monitor of Java2D from JDK1.4 Demo.

Let's take a look at the effect of Memory Monitor.

It can be seen that because there is a while loop, there is a certain time in GC release, during this time, memory consumption is very powerful. The peak reached 923K. The program code is as follows:

//Sysgcmain.java created on 9:15:59

Package com.gx2.system;

/ **

* @Author Frank Gao @version 1.00

* Copy Right By GX2 Studio 2003

* Copyright (C) 2003 Sun Microsystems, Inc. All Rights Reserved.

*

* Redistribution and use in Source ...

* /

/ *

* @ (#) MemoryMonitor.java 1.32

03/01/23

* /

Import java.awt. *;

Import java.awt.event. *;

Import java.awt.image.bufferedImage;

Import java.awt.geom.Line2D;

Import java.awt.geom.Rectangle2d;

Import java.util.date;

Import javax.swing. *;

Import javax.swing.border.etchedborder;

Import javax.swing.border.titledborder;

/ **

* TRACKS MEMORY Allocated & Used, Displayed in Graph Form.

* /

Public class sysgcmain extends jpanel {

Static Jcheckbox Datestampcb = New JCheckBox ("Output Date Stamp");

Public Surface Surf;

JPanel Controls;

Boolean docontrols;

JTextField TF;

Public sysgcmain () {

SetLayout (New BorderLayout ());

SetBorder (New Titledborder (), "Memory Monitor");

Add (Surf = New Surface ());

Controls = new jpanel ();

Controls.SetPreferredSize (New Dimension (135, 80));

Font Font = New Font ("Serif", Font.Plain, 10);

Jlabel label = new Jlabel ("Sample Rate");

Label.SetFont (font);

Label.SetForeground (Color.Black);

Controls.add (label);

Tf = New JtextField ("1000"); TF.SETPREFERREDSIZE (New Dimension (45, 20));

Controls.Add (TF);

Controls.add (label = new jlabel ("ms"));

Label.SetFont (font);

Label.SetForeground (Color.Black);

Controls.add (datestampcb);

Datestampcb.SetFont (font);

AddMouseListener (new mouseadapter () {

Public void mouseclicked (mouseevent e) {

REMOVEAll ();

IF ((DOCONTROLS =! DOCONTROLS)) {

Surf.stop ();

Add (Controls);

} else {

Try {

Surf.SleepAmount = long.parselong (tf.gettext (). Trim ());

} catch (exception ex) {}

Surf.start ();

Add (SURF);

}

Validate ();

Repaint ();

}

});

}

Public Class Surface Extends JPanel IMPLEments Runnable {

Public thread thread;

Public long SleepAmount = 1000;

Private int W, H;

PRIVATE BUFFEREDIMAGE BIMG;

PRIVATE Graphics2D BIG;

Private font font = new font ("Times New Roman", Font.Plain, 11);

Private runtime r = runtime.getRuntime ();

PRIVATE INT Columninc;

Private int PTS [];

Private int ptnum;

PRIVATE INT Ascent, deScent

Private float freememory, totalmemory;

Private Rectangle GraphoutLineRect = New Rectangle ();

Private Rectangle2D mfRect = new rectangle2d.float ();

Private Rectangle2D Murect = New Rectangle2d.float ();

PRIVATE LINE2D graphline = new line2d.float ();

Private color graphcolor = New Color (46, 139, 87);

Private Color Mfcolor = New Color (0, 100, 0);

PRIVATE STRING USEDSTR;

Public Surface () {

SetBackground ;; Color.Black;

AddMouseListener (new mouseadapter () {

Public void mouseclicked (mouseevent e) {

IF (thread == null) start (); else stop ();

}

});

}

Public Dimension GETMINIMUMUMSIZE () {

Return getpreferredsize ();

}

Public Dimension GetMaxImumsize () {

Return getpreferredsize ();

}

Public Dimension GetPreferRedsize () {Return New Dimension (135, 80);

}

Public void paint (graphics g) {

IF (BIG == NULL) {

Return;

}

BIG.SetBackground; GetBackground ());

Big.clearRect (0, 0, W, h);

Float FreeMemory = (float) r.freeMemory ();

FLOAT TOTALMEMORY = (FLOAT) R. TOTALMEMORY ();

// .. draw allocated and use strings ..

BIG.SETCOLOR (Color.green);

Big.drawstring (String.Valueof ((int) TotalMemory / 1024) "k allocated",

4.0F

(float) ascent

0.5F

);

UsedStr = String.Valueof ((int)) / 1024) / 1024)

"K used";

Big.drawstring (useDSTR, 4, H-Descent);

// Calculate Remaining Size

FLOAT SSH = Ascent Descent;

FLOAT Remainingheight = (float) (H - (SSH * 2) -

0.5F

);

Float blockheight = RemainingHeight / 10;

Float blockWidth =

20.0F

;

Float remainingwidth = (float) (W - blockWidth - 10);

// .. Memory Free ..

BIG.SETCOLOR (MFColor);

INT MEMUSAGE = (int) * 10);

INT i = 0;

For (; i

MfRect.setRect (5, (float) ssh i * blockheight,

Blockwidth, (Float) blockHeight-1);

BIG.FILL (MFRECT);

}

// .. Memory used ..

BIG.SETCOLOR (Color.green);

For (; i <10; i ) {

Murect.seTRECT (5, (float) ssh i * blockheight,

Blockwidth, (Float) blockHeight-1);

BIG.FILL (MURECT);

}

// .. Draw History Graph ..

BIG.SETCOLOR (Graphcolor);

INT graphx = 30;

INT graphy = (int) ssh;

INT graphw = w - graphx - 5;

INT graphh = (int) Remainingheight;

GraphoutLineRect.seTRect (Graphx, Graphy, Graphw, Graphh);

BIG.DRAW (GraphouTlineRect);

INT graphrow = graphh / 10;

// .. draw rot ..

For (int J = graphy; j <= graphh graphy; j = graphrow) {graphline.setline (Graphx, J, Graphx graphw, j);

BIG.DRAW (graphline);

}

// .. draw animated column movement ..

INT graphcolumn = graphw / 15;

IF (columninc == 0) {

Columninc = graphcolumn;

}

For (int J = graphx columninc; j

Graphline.setline (j, graphy, j, graphy graphh);

BIG.DRAW (graphline);

}

--columninc;

IF (PTS == NULL) {

PTS = New Int [graphw];

PTNUM = 0;

} else if (PTS.Length! = graphw) {

INT TMP [] = NULL;

IF (Ptnum

TMP = new int [ptnum];

System.ArrayCopy (PTS, 0, TMP, 0, Tmp.Length);

} else {

TMP = new int [graphw];

System.ArrayCopy (PTS, PTS.LENGTH-TMP.LENGTH, TMP, 0, TMP.LENGTH);

Ptnum = Tmp.Length - 2;

}

PTS = New Int [graphw];

System.ArrayCopy (TMP, 0, PTS, 0, Tmp.Length);

} else {

BIG.SETCOLOR (Color.Yellow);

PTS [PTNUM] = (int)) (FreeMemory / Totalmemory);

For (int J = graphx graphw-ptnum, k = 0; k

IF (k! = 0) {

IF (PTS [K]! = PTS [K-1]) {

BIG.DRAWLINE (J-1, PTS [K-1], J, PTS [K]);

} else {

BIG.FILLRECT (J, PTS [K], 1, 1);

}

}

}

IF (PTNUM 2 == PTS.LENGTH) {

// throw out Oldest Point

For (int J = 1; j

PTS [J-1] = PTS [J];

}

--ptnum;

} else {

PTNUM ;

}

}

G.drawImage (BIMG, 0, 0, this);

}

Public void start () {

Thread = new thread (this);

Thread.SetPriority (thread.min_priority);

Thread.setname ("MemoryMonitor");

Thread.start ();

}

Public synchronized void stop () {

thread = null;

NOTIFY ();

}

Public void run () {

Thread me = thread.currentthread (); while (thread == me&&! Isshowing () || getSize (). Width == 0) {

Try {

Thread.sleep (500);

} catCH (InterruptedException E) {Return;}

}

While (thread == me && isshowing ()) {

Dimension D = getSize ();

IF (D.Width! = W || D.height! = h) {

W = d.width;

H = d.height;

BIMG = (BufferedImage) CreateImage (W, H);

BIG = BIMG.CREATEGRAPHICS ();

BIG.SETFONT (FONT);

FontMetrics FM = BIG.GETFONTMETRICS (FONT);

ascent = (int) fm.getascent ();

deScent = (int) fm.getdescent ();

}

Repaint ();

Try {

Thread.sleep (SleepAmount);

} catch (interruptedExcection e) {breaf;}

IF (sysgcmain.datestampcb.isselected ()) {

System.out.println (New Date (). ToString () " UsedStr);

}

// add by forgetting ideal

2004-11-1

// If you don't force GC, because the while loop, the memory will consume very powerful.

/ / Plus the following two sentences to ensure stable memory consumption

Runtime.getRuntime (). FreeMemory ();

Runtime.getRuntime (). Gc ();

}

thread = null;

}

}

Public static void main (string s []) {

Final sysgcmain demo = new sysgcmain ();

Windowlistener L = new windowadapter () {

Public void windowclosing (windowevent e) {system.exit (0);

Public void windowdeiconified (WindowEvent E) {DEMO.SURF.Start ();

Public void windowiconified (WindowEvent E) {DEMO.SURF.STOP ();

}

JButton Button = New JButton ("Force GC");

Button.addActionListener (New ActionListener () {

Public void actionPerformed (ACTIONEvent Event) {

Runtime.getRuntime (). FreeMemory ();

Runtime.getRuntime (). Gc ();

}

});

JFrame f = New Jframe ("Frank Gao - MemoryMonitor");

F.AddWindowListener (L);

F.GetContentPane (). Add ("center", demo);

F.GetContentPane (). add (button, borderlayout.south);

F.PACK (); F.setsize (New Dimension (200, 200));

F.setVisible (TRUE);

Demo.surf.start ();

}

}

Add forced GC in the While cycle, the memory peak is worth a good control maintenance level.

Runtime.getRuntime (). FreeMemory ();

Runtime.getRuntime (). Gc ();

This can be considered that the above method is used to reduce the memory peak, improve memory efficiency.

转载请注明原文地址:https://www.9cbs.com/read-98272.html

New Post(0)