How to release process resource??
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.StringTokenizer;
public class RuntimeSample{
public RuntimeSample() {
}
private void execCmd1() throws IOException {
InputStream in = null;
Process process = null;
String[] cmd = { "java", "-version" };
try {
process = Runtime.getRuntime().exec(cmd);
in = process.getInputStream();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
in.close();
}
}
}
private void execCmd2() throws IOException {
Process process = null;
String[] cmd = { "java", "-version" };
try {
process = Runtime.getRuntime().exec(cmd);
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
}
why it is throwing process.getError stream is not closed,I tried to close process resource by using following
if (process != null) {
process.getInputStream().close();
process.getOutputStream().close();
process.getErrorStream().close();
even it is showing process.getError stream is not closed.may i know the reason y it is showing that stream is not closed and how to close the process resource.Thanks in advance
I know this answer is somewhat late, but maybe someone else runs into the same issue.
In my project the Server runs some utility (I call it winps.exe here) regularly and it was easy to see (using RAMMAP resp. Handles) that the Java process kept a handle to each of the (terminated) child processes. Restarting the Server removed all entries from the process table.
After some experimenting, I found that explicitly calling the Garbage Collector resolved the issue.
Below you find my Java test program which I used to investigate the matter.
Note that this test program has been copied from the Server source code and isn't 100% as cleanly written as possible.
import java.util.*;
import java.io.*;
import java.util.regex.*;
import java.text.*;
import java.lang.reflect.*;
import java.util.concurrent.TimeUnit;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
public class StartPS
{
static Long STARTTIME_JITTER = 5000L;
synchronized public static HashMap<String,Long> getStartTimes()
{
HashMap<String,Long> result = new HashMap<String, Long>();;
final File tmp_file = new File("/tmp/starttimes.out");
String tmpfilename = null;
try {
tmpfilename = tmp_file.getCanonicalPath();
} catch (Exception e) {}
try {
ProcessBuilder pb = new ProcessBuilder(".\\winps.exe");
pb.redirectOutput(new File(tmpfilename));
pb.redirectErrorStream(true);
Process p = pb.start();
p.getOutputStream().close();
p.getInputStream().close();
p.getErrorStream().close();
try {
p.waitFor();
} catch (InterruptedException ie) {
// maybe some cleanup here
}
try {
while (p.isAlive()) { // <- most likely unnecessary ;-)
Thread.sleep(100);
p.destroy();
System.gc();
}
p = null; // should help the garbage collector (eliminates a reference to the object p points to)
System.gc(); // <- most likely the key to success !
} catch (Exception e) {
System.out.println("Warning: " + e.toString());
}
} catch (Exception e) {
throw new RuntimeException("(02310251044) Process start times : " + e.toString());
}
return result;
}
public static void main(String[] argv)
{
String sMax;
int iMax = 500;
if (argv.length > 0) {
sMax = argv[0];
try {
iMax = Integer.parseInt(sMax);
} catch (Exception e) {
System.out.println("Oops : " + e.toString());
System.exit(1);
}
}
for (int i = 0; i < iMax; ++i) {
System.out.print("\r" + i);
getStartTimes();
try {
Thread.sleep(1000);
} catch (Exception e) {
// do nothing
}
}
}
}
Related
I have this piece of code.
// On a thread
try {
WatchService watcher = FileSystems.getDefault().newWatchService();
Path directory = Paths.get("properties");
WatchKey watchKey = directory.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY);
while (true) {
for (WatchEvent<?> event : watchKey.pollEvents()) {
Path changed = (Path) event.context();
if (changed.toString().equals("radar.properties")) {
System.out.println("read call:");
readProperties();
}
}
if (!watchKey.reset()) {
break;
}
}
} catch (IOException e) {
FCSLogger.LOGGER.log(Level.SEVERE, "Exception while setting up WatchService", e);
}
// Method called by the above code
private void readProperties() {
try {
InputStream input = new FileInputStream(Paths.get("properties", "radar.properties").toString());
Properties prop = new Properties();
prop.load(input);
updateRate = Integer.parseInt(prop.getProperty("updateRate"));
System.out.println(updateRate);
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
It returns the right result on the first call and then blocks the whole thread. I've isolated the bug to be in this method since everything else works flawlessly when there is no calling this method. I'm wondering what am I doing wrong here.
Snapshot of console output:
// First change of file:
read call:
10
read call:
10
// Second change of file:
read call:
// I keep changing but nothing happens:
It can be that readProperties throws NumberFormatException, and that causes your watcher thread to exit.
You could wrap calls to readProperties and catch exceptions; so that at least the watcher will keep watching in case of exceptions.
And you should use take, so that the watcher thread blocks. Your current solution causes 100% cpu usage.
See below the modified code. I added a writer thread to update the file, and (unsurprisingly?) readProperties can fail since we are accessing the file while it is being written. A possible output is:
....
property=5000
property=null
java.lang.NumberFormatException: null
at java.base/java.lang.Integer.parseInt(Integer.java:614)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at cl.ClientPoll.readProperties(ClientPoll.java:26)
at cl.ClientPoll.run(ClientPoll.java:46)
property=6000
property=7000
....
So when watching, you can either: skip on error and continue; or use other APIs so that the file being written is locked while writing.
Sample code
package cl;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.Properties;
public class ClientPoll extends Thread {
private void readProperties() {
try {
Path path = Paths.get("radar.properties");
InputStream input =new FileInputStream(path.toString());
Properties prop = new Properties();
prop.load(input);
String property = prop.getProperty("updateRate");
System.out.println("property="+property);
int updateRate = Integer.parseInt(property);
// System.out.println(updateRate);
input.close();
} catch (IOException e) {
e.printStackTrace(System.out);
}
}
#Override
public void run() {
try {
WatchService watcher = FileSystems.getDefault().newWatchService();
Path directory = Paths.get(".");
WatchKey watchKey = directory.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY);
while (true) {
WatchKey wk = watcher.take();
for (WatchEvent<?> event : wk.pollEvents()) {
Path changed = (Path) event.context();
if (changed.toString().equals("radar.properties")) {
try {
readProperties();
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
}
if (!watchKey.reset()) {
break;
}
}
} catch (IOException e) {
e.printStackTrace(System.out);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new ClientPoll().start();
new Writer().start();
}
}
class Writer extends Thread {
#Override
public void run() {
try {
for (int i=0;i<10;i++) {
File f = new File("radar.properties");
FileWriter fw = new FileWriter(f);
fw.write("updateRate="+i*1000);
fw.close();
sleep(1000L);
}
} catch (Exception e) {
e.printStackTrace(System.out);
}
System.out.println("exit");
System.exit(0);
}
}
Using Java program I am opening an external application( for example: notepad). How can i get coordinates/location of external application for screen capture/screen-shots.
I can take screen-shots of the whole window, but not for a particular application.
I have already tried "Robot" for screen capturing but not able to capture a particular area as I am not able to find the location and size of the application window.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
public class AppCheck {
public static void main(String[] args) {
System.out.println("***********************");
try {
System.out.println("Opening notepad");
Runtime runTime = Runtime.getRuntime();
Process process = runTime.exec("notepad");
try {
int count=0;
while(process.isAlive())
{
System.out.println("process name : " + process.getClass().getName());
Field f = process.getClass().getDeclaredField("handle");
f.setAccessible(true);
long handl = f.getLong(process);
System.out.println("Process ID : " + handl);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Closing notepad");
process.destroy();
} catch (Exception ex) {
System.out.println(ex);
}
System.out.println("************************************");
}
}
I was testing out writing to files with this code:
package files;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
public class FileTest1
{
public static void main(String[] args)
{
try
{
try
{
File f = new File("filetest1.txt");
FileWriter fWrite = new FileWriter(f);
BufferedWriter fileWrite = new BufferedWriter(fWrite);
fileWrite.write("This is a test!");
}
catch(FileNotFoundException e)
{
System.out.print("A FileNotFoundException occurred!");
e.printStackTrace();
}
}
catch(IOException e)
{
System.out.println("An IOException occurred!:");
e.printStackTrace();
}
}
}
Nothing happens when it is executed.
"This is a test!" is not written, nor the StackTrace or the "A/An [exception] occurred!"...
I don't know what's causing the problem. I have fileTest1.txt in the package right under the file...
A BufferedWriter does just that, it buffers the output before it is written to the destination. This can make the BufferedWriter faster to use as it doesn't have to write to a slow destination, like a disk or socket, straight away.
The contents will be written when the internal buffer is to full, you flush the Writer or close the writer
Remember, if you open it, you should close it...
For example...
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class TestFileWriter {
public static void main(String[] args) {
try {
BufferedWriter fileWrite = null;
try {
File f = new File("filetest1.txt");
System.out.println("Writing to " + f.getCanonicalPath());
FileWriter fWrite = new FileWriter(f);
fileWrite = new BufferedWriter(fWrite);
fileWrite.write("This is a test!");
fileWrite.flush();
} catch (FileNotFoundException e) {
System.out.print("A FileNotFoundException occurred!");
e.printStackTrace();
} finally {
try {
// Note, BufferedWriter#close will also close
// the parent Writer...
fileWrite.close();
} catch (Exception exp) {
}
}
} catch (IOException e) {
System.out.println("An IOException occurred!:");
e.printStackTrace();
}
try {
BufferedReader br = null;
try {
File f = new File("filetest1.txt");
System.out.println("Reading from " + f.getCanonicalPath());
FileReader fReader = new FileReader(f);
br = new BufferedReader(fReader);
String text = null;
while ((text = br.readLine()) != null) {
System.out.println(text);
}
} catch (FileNotFoundException e) {
System.out.print("A FileNotFoundException occurred!");
e.printStackTrace();
} finally {
try {
// Note, BufferedWriter#close will also close
// the parent Writer...
br.close();
} catch (Exception exp) {
}
}
} catch (IOException e) {
System.out.println("An IOException occurred!:");
e.printStackTrace();
}
}
}
If you are using Java 7, you may like to take a look at try-with-resources
After
fileWrite.write("This is a test!");
you have to flush() the writer. To avoid leaking of resources you should also close() the writer (which automatically flushes it).
So you need to add:
fileWrite.close();
Use BufferedWriter.flush() and BufferedWriter.close(). Additional info here http://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html
You must call close() or at least flush() on the writer in order for the buffer to be really written to the file.
/*main method*/
Server server = new Server(tcpPort);
new Thread(server).start();
try {
Thread.sleep(1000*60); /* 60 seconds*/
} catch (InterruptedException e) {
e.printStackTrace();
}
server.stop;
...
This is the code I've written. A Server thread is started, and runs for 60 seconds. How do I change this to run infinitely, ending when a user enters Enter via a BufferedReader or something.
I've tried it with
while(!input.equals("")) { /* just pseudocoded here...*/
Thread.sleep(10);
}
but this will my Server stop from working correctly. My clients won't even connect to it anymore. Have I made a design mistake or is this an easy problem to solve?
Try this basic Chatting Server that I wrote. This server simply keeps running in loop and broadcast the message send by the clients to all the other clients associated with this server.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class Server {
// ///----------------------------------------Instance Variable Fields
ServerSocket ss = null;
Socket incoming = null;
// ///----------------------------------------Instance Variable Fields
// ///---------------------------------------- static Variable Fields
public static ArrayList<Socket> socList = new ArrayList<Socket>();
// ///---------------------------------------- static Variable Fields
public void go() {
try {
ss = new ServerSocket(25005);
while (true) {
incoming = ss.accept();
socList.add(incoming);
System.out.println("Incoming: " + incoming);
new Thread(new ClientHandleKaro(incoming)).start();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
ss.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class ClientHandleKaro implements Runnable {
InputStream is = null;
OutputStream os = null;
InputStreamReader isr = null;
BufferedReader br = null;
PrintWriter pw = null;
boolean isDone = false;
Socket sInThread = null;
public ClientHandleKaro(Socket sxxx) {
this.sInThread = sxxx;
}
#Override
public void run() {
if (sInThread.isConnected()) {
System.out.println("Welcamu Clienta");
System.out.println(socList);
}
try {
is = sInThread.getInputStream();
System.out.println("IS: " + is);
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
os = sInThread.getOutputStream();
pw = new PrintWriter(os, true);
String s = new String();
while ((!isDone) && (s = br.readLine()) != null) {
String[] asx = s.split("-");
System.out.println("On Console: " + s);
// pw.println(s);
Thread tx = new Thread(new ReplyKaroToClient(s,
this.sInThread));
tx.start();
if (asx[1].trim().equalsIgnoreCase("BYE")) {
System.out.println("I am inside Bye");
isDone = true;
}
}
} catch (IOException e) {
System.out.println("Thanks for Chatting.....");
} finally {
try {
Thread tiku = new Thread(new ByeByeKarDo(sInThread));
tiku.start();
try {
tiku.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Accha to hum Chalte hain !!!");
System.out.println(socList);
br.close();
pw.close();
sInThread.close();
} catch (IOException e) {
}
}
}
}
class ReplyKaroToClient implements Runnable {
public String mString;
public Socket mSocket;
public ReplyKaroToClient(String s, Socket sIn) {
this.mString = s;
this.mSocket = sIn;
}
#Override
public void run() {
for (Socket sRaW : socList) {
if (mSocket.equals(sRaW)) {
System.out.println("Mai same hun");
continue;
} else {
try {
new PrintWriter(sRaW.getOutputStream(), true)
.println(mString);
} catch (IOException e) {
System.out.println("Its in Catch");
}
}
}
}
}
class ByeByeKarDo implements Runnable {
Socket inCom;
public ByeByeKarDo(Socket si) {
this.inCom = si;
}
#Override
public void run() {
try {
new PrintWriter(inCom.getOutputStream(), true)
.println("You have Logged Out of Server... Thanks for ur Visit");
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new Server().go();
}
}
Start with this SO thread: How to create a basic Java Server? . It will give you an example how to write a very simple server.
Key thing to note there is the serverSocket.accept() . It will block - in other words it will WAIT forever for a client to connect, or it will fail in the case of some error. Once a client is connected, you will get a clientSocket that you can use to read what client wrote, and also write to it.
It is really a good starting point for understanding Java network programming. However, I recommend you read more about this topic. Something like this: http://beej.us/guide/bgnet/
I want to run a radio station from a hill top with the studio in the valley using a radio Ethernet link of 1.1 mbs data rate below is an example code (below) that I found.
But I want the code to:
Load a text file containing the IPv4 IP address to receive sound
Read a true or false from the file re transmit from the android for another to receive to save data on such a slow connection.
Can someone help please?
import java.io.IOException;
import java.util.Vector;
import javax.media.CaptureDeviceInfo;
import javax.media.CaptureDeviceManager;
import javax.media.DataSink;
import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.NoPlayerException;
import javax.media.NoProcessorException;
import javax.media.NotRealizedError;
import javax.media.Player;
import javax.media.Processor;
import javax.media.control.FormatControl;
import javax.media.control.TrackControl;
import javax.media.format.AudioFormat;
import javax.media.protocol.ContentDescriptor;
import javax.media.protocol.DataSource;
public class SimpleVoiceTransmiter {
/**
* #param args
*/
public static void main(String[] args) {
// First find a capture device that will capture linear audio
// data at 8bit 8Khz
AudioFormat format= new AudioFormat(AudioFormat.LINEAR, 8000, 8, 1);
Vector devices= CaptureDeviceManager.getDeviceList( format);
CaptureDeviceInfo di= null;
if (devices.size() > 0) {
di = (CaptureDeviceInfo) devices.elementAt( 0);
}
else {
// exit if we could not find the relevant capturedevice.
System.exit(-1);
}
// Create a processor for this capturedevice & exit if we
// cannot create it
Processor processor = null;
try {
processor = Manager.createProcessor(di.getLocator());
} catch (IOException e) {
System.exit(-1);
} catch (NoProcessorException e) {
System.exit(-1);
}
// configure the processor
processor.configure();
while (processor.getState() != Processor.Configured){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
processor.setContentDescriptor(
new ContentDescriptor( ContentDescriptor.RAW));
TrackControl track[] = processor.getTrackControls();
boolean encodingOk = false;
// Go through the tracks and try to program one of them to
// output gsm data.
for (int i = 0; i < track.length; i++) {
if (!encodingOk && track[i] instanceof FormatControl) {
if (((FormatControl)track[i]).
setFormat( new AudioFormat(AudioFormat.GSM_RTP, 8000, 8, 1)) == null) {
track[i].setEnabled(false);
}
else {
encodingOk = true;
}
} else {
// we could not set this track to gsm, so disable it
track[i].setEnabled(false);
}
}
// At this point, we have determined where we can send out
// gsm data or not.
// realize the processor
if (encodingOk) {
processor.realize();
while (processor.getState() != Processor.Realized){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// get the output datasource of the processor and exit
// if we fail
DataSource ds = null;
try {
ds = processor.getDataOutput();
} catch (NotRealizedError e) {
System.exit(-1);
}
// hand this datasource to manager for creating an RTP
// datasink our RTP datasink will multicast the audio
try {
String url= "rtp://224.0.0.1:22224/audio/16";
MediaLocator m = new MediaLocator(url);
DataSink d = Manager.createDataSink(ds, m);
d.open();
d.start();
processor.start();
} catch (Exception e) {
System.exit(-1);
}
}
}
}
Receiver:
import java.io.IOException;
import java.net.MalformedURLException;
import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.NoPlayerException;
import javax.media.Player;
public class SimpleVoiceReciver{
/**
* #param args
*/
public static void main(String[] args) {
String url= "rtp://192.168.1.111:22224/audio/16";
MediaLocator mrl= new MediaLocator(url);
if (mrl == null) {
System.err.println("Can't build MRL for RTP");
System.exit(-1);
}
// Create a player for this rtp session
Player player = null;
try {
player = Manager.createPlayer(mrl);
} catch (NoPlayerException e) {
System.err.println("Error:" + e);
System.exit(-1);
} catch (MalformedURLException e) {
System.err.println("Error:" + e);
System.exit(-1);
} catch (IOException e) {
System.err.println("Error:" + e);
System.exit(-1);
}
if (player != null) {
System.out.println("Player created.");
player.realize();
// wait for realizing
while (player.getState() != Player.Realized){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
player.start();
} else {
System.err.println("Player doesn't created.");
System.exit(-1);
}
}
}
It sounds perfectly possible to do this multicasting over a local network. AFAIK this will not work across the internet. Also see this : Device support for multicasting is apparently very patchy. So do your research, and make sure the Android devices you work with actually support this on a software and hardware level - many of them do not. Caveat Emptor.