Memory Management

Although Java provides automatic garbage collection, sometimes you will want to know how large the object heap is and how much of it is left. You can use this information, for example, to check your code for efficiency or to approximate how many more objects of a certain type, can be instantiated. To obtain these values, use the total Memory( ) and free Memory( ) methods:.As we mentioned in Par~ I, Java’s garbage collector runs periodically to recycle unused objects. However, sometimes you will want to collect discarded objects prior to the collector’s next appointed rounds. You can run the garbage collector on demand by calling the get( ) method. A good thing to try is to call get() and then call freemasonry ) to get a baseline memory usage ..Next, execute your code and call free Memory( ) again to see how much memory it is allocating. The following program illustrates this idea: Sample output from this program is shown here (of course, your actual results may vary): Total memory is: 1048568 Initial free memory: 751392 Free memory after garbage collection:

841424 Free memory after allocation: ‘824000 Memory used by allocation: 17424 Free memory after collecting discarded Integers: 842640

Executing Other Programs

In safe environs meets, you can use Java to execute other heavyweight processes (that is, programs) on multitasking operating system. Several forms of the exec() method allow you to name-the program you want to run as well as its input parameters. The excel ) method returns a Process object, which can then be used to control how your Java program interacts with this new running process. Because lava can run on a variety of platforms and under a variety of operating systems, execute ) is inherently  environment-dependent.

The following example uses exec ) to launch notepad, Windows’ simple text editor. Obviously, this example must be run under the Windows operating system. There are several alternate forms of expect ), but the one shown in the example is the most common. The Process object returned by excel ) can be manipulated by Process’methods after’ the new program starts running. You can kill the sub process with the ‘destroy I method. The wait For() method causes your program to wait until the sub process finishes. The exitvaluet ) method returns the value returned by the. sub process when it is finished. This is typically 0 if problems occur. Here is the ‘preceding exec( ) example modified’ to wait for the running process to exit: Which ;sub process is running, you Gin to and read from its standard input and output.The get Output Stream() and prearrangement ) methods return the handles to standard in and out of the sub process.

[vfb id=1]

Share This