Java with Shell equal 美酒加咖啡

 

Chemistry we learned that "hydrogen plus oxygen in case of ignition will generate water."

 

We learned that in life "would get the daughter of Spring Night moment the case of a really good time plus views."

 

Technically is it not so? Assume a scenario: BOSS allows you to achieve a service monitoring control room, to see the remaining disk space for each server, to see. . . can see. . .

 

In fact, speaking really, to realize there are a lot of ideas, but whether black or white as it catches mice is a good cat, and today we try to match it with Java and Shell, will have to see whether the surprise reaction.

 

1. 

First through JDK source code, product a product Runtime cup of wine.

 

640?wx_fmt=png

 

The figure is the removal of part of the JDK Runtime source, is divided into 4 large code segments her general knowledge.

 

The first piece of code segments , can be seen constructed privatization Runtime, provides static properties, and create instances in advance, and provides a static method to get the instance, it is not that the singleton design pattern What, ask the interviewer when there is design patterns, take Kuangpen.

 

The second block of code segments , mainly addShutdownHook () method, adding closed hook, bluntly said, in fact, allows developers to insert code section executed in the JVM closed. For example, when building services framework, the face needs to be done to stop taking elegant, clean up the battlefield, the release of resources, etc., are very useful in scenarios such as these. Wherein Tomcat, Jetty container such as can be seen in figure shutdownHook.

Runtime = Runtime.getRuntime Runtime ();	 
Runtime.addShutdownHook (new new the Thread () {	 
    @Override	 
    public void RUN () {	 
        System.out.println ( "sweep the battlefield, the release of resources to complete the elegant stop taking");	 
    }	 
});	 
System.out.println ( "service startup complete");

  

Code runs effect is as follows.

Services startup is complete	 
sweep the battlefield, the release of resources to complete the elegant stop taking

  

The third block of code segments , mainly to show the series for the JDK Runtime exec overloaded methods provided, this is the focus of this share, the highlight of the final say.

 

A fourth code segment blocks , mainly some system information acquisition API Runtime provided directly throw code used on the line take.

Runtime = Runtime.getRuntime the Runtime ();	 
System.out.println (String.format ( "the JVM available native CPU Cores D%", runtime.availableProcessors ()));	 
// defaults to the system 1/4	 
the System. out.println (String.format ( "maximum available memory space M D%", runtime.maxMemory () / 1024/1024));	 
// default system 1/64	 
System.out.println (String.format ( " available memory space M D% ", Runtime.totalMemory () / 1024/1024));	 
System.out.println (String.format (" free memory space% d M ", runtime.freeMemory () / 1024/1024)) ;

  

Output code runs as follows, in fact, a real environment might render template engine FreeMarker, then e-mail alert, achieve higher force grid.

 

2. 

Prior to detail Runtime.exec () the main event, then this product a product df coffee.

 

Linux df command to display the current disk usage on the system of statistics, mainly used to view disk space partition disk is used, the remaining space.

Command is as follows:

df [选项]... [FILE]...

Common options are as follows:

640?wx_fmt=jpeg

 

3. 

Runtime wine plus coffee Shell What will happen then?

Main event began, back Runtime source code, we see exec () family methods will help us start a Process process, it may wish to take a closer look into the incoming command df -h.

class Foo {public	 

	
    public static void main (String [] args) throws Exception {	 
        // DF command to see if the disk partition, the disk space has been used, the remaining space	 
        // df -h in appropriate units to display information	 
        System .out.println (Exec ( "DF -H"));	 
    }	 

	
    Private static String Exec (Command String) throws Exception {	 
        String [] = {cmd "/ bin / SH", "-C", Command};	 
        the StringBuilder OUT the StringBuilder new new = ();	 
        the BufferedReader Reader = null;	 
        the InputStream in = null;	 
        the try {	 
            . = Runtime.getRuntime Process Process () Exec (cmd);	 
            in Process.getInputStream = ();	  
            Reader the BufferedReader new new = (new new the InputStreamReader (in) );	
            String Line;	 
            the while ((Line = Reader. readLine ())! = null)	 {
                out.append(line + "\n");	
            }	
            process.waitFor();	
        } finally {	
            if (reader != null) {	
                reader.close();	
            }	
        }	
        return out.toString();	
    }	
}

  

The code will find the call waitFor process of () method, which effect causes the current thread to wait until the process represented by this Process object is terminated, in fact, it is to wait for all the things Process exec which started in both dry End ( the problem most production out here ), the code following operation effect.

 

640?wx_fmt=png

 

The effect is indeed possible, so that way, want to monitor what the statistics function, may wish to direct the command to execute Java programs can be.

 

4. 

If you focus on a small ape partners should speak clearly, in the " Runtime and ProcessBuilder the main difference is Shane?

 

  • In fact, the Runtime.exec () method of design, a single acceptable string that is to separate executable command programs and parameters through the space; of course, be acceptable string array parameter.

    640?wx_fmt=png

  • As shown above, ProcessBuilder process parameters into a List <String> or more strings .

  • The same point is ProcessBuilder.start () and Runtime.exec () methods are used to create an operating system process (command line operations).

 

5. 

Well, a few minutes of simple sharing, the main contacts and let you really know about Runtime, hoping to help you even better at work.

 

Finally, still give a sword in three new six-pulse pulse Ali everyone: Today's best performance is the minimum requirement tomorrow; at the moment I'm yours; serious life happy work!

Guess you like

Origin www.cnblogs.com/socoool/p/12629766.html