Created
July 21, 2011 09:49
-
-
Save davidB/1096881 to your computer and use it in GitHub Desktop.
I used the following code to check if Thread of java process can have independent state
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// I used the following code to check if Thread of java process can have independent state with | |
// ps -Teo state,pcpu,pmem,nlwp,pid,spid,user,args |grep FakeThread | |
import java.io.File; | |
import java.io.FileOutputStream; | |
import java.io.IOException; | |
// The goal is to create several Thread that should be in different state and check if ps or other catch the correct state of the thread | |
public class FakeThreadState { | |
/** | |
* @param args | |
*/ | |
public static void main(String[] args) { | |
Thread waitingRunnable = new Thread(){ | |
@Override | |
public void run() { | |
try { | |
Object lock = new Object(); | |
synchronized(lock) { | |
lock.wait(); | |
} | |
} catch (InterruptedException e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
}; | |
}; | |
}; | |
Thread sleepingRunnable = new Thread(){ | |
@Override | |
public void run() { | |
try { | |
sleep(60*60*1000); | |
} catch (InterruptedException e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
} //1H | |
}; | |
}; | |
Thread summingRunnable = new Thread(){ | |
@Override | |
public void run() { | |
long l = 0; | |
long op = +1; | |
while(true) { | |
l = l + op; | |
if (l == 1000) { | |
op = -1; | |
} else if (l == 0) { | |
op = +1; | |
} | |
} | |
}; | |
}; | |
Thread ioRunnable = new Thread(){ | |
@Override | |
public void run() { | |
try { | |
File f = new File("/tmp/z"); | |
f.deleteOnExit(); | |
FileOutputStream os = null; | |
try { | |
long i = 0; | |
while(true) { | |
if (i % 1000 == 0) { | |
if (os != null) os.close(); | |
os = new FileOutputStream(f); | |
} | |
if (os != null) { | |
os.write(33); | |
os.flush(); | |
} | |
i++; | |
} | |
} finally { | |
if (os != null) os.close(); | |
} | |
} catch (IOException e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
} | |
}; | |
}; | |
waitingRunnable.start(); | |
sleepingRunnable.start(); | |
summingRunnable.start(); | |
ioRunnable.start(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment