Why Visual VM shows instances as zero for this String class? - java

This is my sample program which creates a String Object
public class TestingHeap {
public static void main(String args[])
{
String str = new String("Hi This is sample String");
try {
//Thread.sleep(1111111);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
When i viewed the Heap Dump under VisualVM Tool the instances for that class is shown as zero
This is the screenshot wrt to above statement
If my assumption is wrong could you please let me know how to see the Objects present under Heap ??

Because your main() method is static and your code doesn't create an instance of TestingHeap. You could do so,
TestingHeap th = new TestingHeap(); // <-- add to main.

Related

Can we have two statements in a try block?

I am new to programming, and am currently in product management. So I am learning the ropes. I tried this statement:
public class Tuna {
Formatter f;
public void createfile(){
try{
f = new Formatter("help.text");
f.format("%s%s", "firstname ","lastname");
}
catch (Exception e){
System.out.println("You got an error ");
}
}
Now the first statement executes and a file is created, but the second statement does not execute by creating an entry into the file.
At the same time when I created a method called createrecord() and inserted the f.format(..); statement it worked.
Can anyone tell me how all of this works?
First, you should never catch Exception. Instead, be as specific as possible in watch exception type to catch. In this case it would be FileNotFoundException.
Secondly, you have to close your formatter so it will actually release the file and make the edits.
Example that works for me:
public class SO41304560 {
public static void main(String[] args) throws Exception {
try {
Formatter formatter = new Formatter("c:/Temp/test.txt");
formatter.format("%s%s", "firstname ","lastname");
formatter.close();
} catch (FileNotFoundException e) {
throw new Exception(e);
}
}
}
As Formatter is AutoClosable, you can also use a try with resources:
public class SO41304560 {
public static void main(String[] args) throws Exception {
try (Formatter formatter = new Formatter("c:/Temp/test.txt")){
formatter.format("%s%s", "firstname ","lastname");
} catch (FileNotFoundException e) {
throw new Exception(e);
}
}
}
Yes, you can put as much code as your heart desires in a try block (but there's something to be said about how much and what you SHOULD).
First order of business, and this should always be the first thing you check. Is your filename right? Does it have a prefix of .text or .txt?
Also don't forget to flush your formatter once you're done. Call f.flush(); when you're done with it
Yes, there is no limit on the quantity of the code to put inside a try block, it depends on how much you need to control the execution of the code based on the exceptions.

java arraylist returning same object by remove method in java 8

I have two thread which are sharing same list, fist thread adding new object in list, and second is performing the remove on same list. after some time of start both thread i got same object, why and how?
JAVA code:
SubmitJob adding ThreadRuning class in to list.
public class SubmitJob extends Thread{
public SubmitJob(List l){
list = l;
}
List<ThreadRuning> list;
private static int counter =0;
public void run(){
while(true){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ThreadRuning t = new ThreadRuning();
t.setThreadname("Thread Name "+counter);
t.setStarttime(new Date().getTime());
list.add(t);
//System.out.println("Submited"+t.getThreadname());
counter++;
}
}
}
Second class is just removing object from list.
public class JobMoniter extends Thread {
public JobMoniter(List l){
list = l;
}
List<ThreadRuning> list;
public void run() {
while (true) {
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (list.size()>0) {
ThreadRuning t = list.remove(0);
System.out.println(t.getState()+" name "+t.getThreadname());
if(t!=null)t.start();
//System.out.println("Startinf job"+t.getThreadname());
}
}
}
}
When i get error java.lang.IllegalThreadStateException i was think it is related thread issue, after some study i found because of trying to start same thread twice. and getting this error so i pint the name of thread which i get from list than i know the remove method is returning same object twice once list size is increase, it is possible in java?
rest of code is below.
public class ThreadUtile {
public static void main(String[] args) {
List<ThreadRuning> list = new ArrayList<ThreadRuning>();
new SubmitJob(list).start();
new JobMoniter(list).start();
}
}
ThreadRuning class:
public class ThreadRuning extends Thread{
private long starttime;
private String threadname;
public void run(){
for(int i=0;i<10;i++){
//System.out.println("Name of Thread "+threadname+ "Executing times"+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// getter setter.
}
Note: i google but did not why?
And if i remove the t.start() part from JobMoniter class and store the thread name in string and compare next time i found same name multiple time, but not each time.
For any further query write in comment.
Beside the fact that you are trying to work in a concurrent environment on an ArrayList, you should really understand what references are in Java.
if (list.size()>0) {
ThreadRuning t = list.remove(0);
System.out.println(t.getState()+" name "+t.getThreadname());
if(t!=null)t.start();
//System.out.println("Startinf job"+t.getThreadname());
}
The method ArrayList.remove(int index) returns the removed object. It does not create a new instance of it. That's why you are getting IllegalThreadStateException when you try to start the Thread again.
When you share an object, it needs to be thread safe to avoid unpredictable behavior that leads to bugs hard to fix. Here your share an ArrayList that is not thread safe, you should use a thread safe collection instead. If you really need a List, simply use the decorator Collections.synchronizedList(List) as next:
List<ThreadRuning> list = Collections.synchronizedList(new ArrayList<ThreadRuning>());
new SubmitJob(list).start();
new JobMoniter(list).start();
However a Queue seems to be much more appropriate, a ConcurrentLinkedQueue (which is a Queue implementation natively thread safe) could be a good choice here.

Can I do 'global Shared Object' in Java?

I have two CLASS(each has a thread), and I want to create a queue shared between them. So one class could write some bytes to the queue, and the other can read from the SAME queue.
I tried static, and here are my codes:
public class ShareQueueTest {
public static final BlockingQueue<byte[]> memshare= new ArrayBlockingQueue<>(1000);
public static void main(String[] args){
Thread a = new Thread(){public void run(){
for(;;){
try {
memshare.put(new byte[20]);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(memshare.size());
}
}};
a.start();
}
}
And the other class is simple read from this queue.
public class ShareQueueTest2 {
public static void main(String[] args){
Thread a = new Thread(){public void run(){
for(;;){
System.out.println(ShareQueueTest.memshare.size());
}
}};
a.start();
}
}
I run it. Though one thread is putting bytes in this queue, the other is still saying the queue is empty all the time. So clearly they are referred to the different things.
ALL the thing happens in local machine.
As this question is simplified from a network scenario, so for some reason, I don't want another class to manipulate those two threads, they are blind to each other. Perhaps the only thing they know for each other is that each thread running on the same local machine, plus, they know the port numbers of the other. Under such condition, I need some methodologies to create a data structure which both of them can 'see'.
I also think of using memory address. Like one class get the memory address of the object, and the other get the object from the address and cast it to the correct data structure. Is it possible in java?
Any help will be appreciated!
Since both of your classes have a main method, it appears that you may be running these two classes in separate processes (instances of the JVM)
If you call ShareQueueTest2.main(...) from ShareQueueTest.main, it should work
If you call the two classes separately, it would spawn two separate JVMs which are two separate processes. The thread cannot communicate across processes via a shared queue.
You need to start both the threads from the same code as the other answers point out. Then you can access the shared variables and see the changes done by one thread get reflected in the other thread.
Try this :
public class ShareQueueTest {
public static final BlockingQueue<byte[]> memshare= new ArrayBlockingQueue<>(1000);
public static void subMain(String[] args){
Thread a = new Thread(){public void run(){
for(;;){
try {
memshare.put(new byte[20]);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(memshare.size());
}
}};
a.start();
}
}
public class ShareQueueTest2 {
public static void subMain(String[] args){
Thread a = new Thread(){public void run(){
for(;;){
System.out.println(ShareQueueTest.memshare.size());
}
}};
a.start();
}
}
public class Launch
{
public static void main( String[] args)
{
ShareQueueTest1.subMain(args);
ShareQueueTest2.subMain(args);
}
}

How to find out , if same method is getting called from catch block or not in java?

I have one method for e.g. void abc(){} and this method is getting called from my main() method directly as well as from it's exception block i.e from catch block too.
Now I wants to find out inside abc() method , whether abc() is getting called normally (i.e. from main()) or it is called in exception case (i.e. from catch() block).
I tried this , using Thread.getCurrentStackTrace() , however it always returns main() method (as method name), as in both cases method will always remain same.
Important point here is , I can not change signature of abc()method and I can not set any flag inside main() method or in catch() block , with this limitations, I am trying to find out , how to check from where abc() get called or in simple words....how to find out whether exception is thrown or not inside abc() method.
Please suggest!
Using StackTraceElement, you might get the line number from which you can figure out whether abc() is called from catch block of main() or not.
See here.
It is something similar to what you have already tried but there you get the line number.
Note: This will work only if you have source code of main method to see line number. Won't work if main is in external jar whose source code is not available to you.
EDIT: Also, this won't work if the external jar is created without line number debug information.
Thread.getCurrentStackTrace() will obviously don't work since whether you call it from main or it is called from catch in either case thread will remain same.
Than what are the options, first you can do what #Eran suggested and I am not repeating that answer, If you don't want to change the method signature another thing that you can do is to set/unset a boolean variable before calling abc() from catch block.. see below example
private static boolean isCalledFromCatch = false;
public static void method ()
{
if(isCalledFromCatch){
//Catch specific processing here
}else{
//main specific processing here
}
}
public static void main (String[] args)
{
try {
isCalledFromCatch = false;
abc();
}
catch (Exception exc) {
isCalledFromCatch = true;
abc();
}
}
However if one function needs to be called from try and catch both, better will be to call it from finally block. That way you don't need to call it from two separate places.
You can pass a boolean parameter to your method that would let it know where it was called from.
public static void abc(boolean isError)
{
if (isError) {
// method was called from catch block
}
}
public static void main (String[] args)
{
try {
...
abc(false);
...
}
catch (Exception exc) {
abc(true);
}
}
You can add a String parameter to your method:
public static void method (String msg)
{
}
public static void someOtherMethod(){
method("calling from someOtherMethod");
}
public static void main (String[] args)
{
try {
method("calling from main");
}
catch (Exception exc) {
method("an exception is thrown" );
}
someOtherMethod(){
}
}
I could think of some solutions:
with an additional input for abc(), detect where your method called. If you want to change method abc's functionallity if an error occured use this approach.
use log. Print log where you see the error. and I recommend this approach, because your method signature remain the same.
add an static variable in your class(like a boolean) and set this variable when error occurred and check this variable in abc.

Run a .java file using ProcessBuilder

I'm a novice programmer working in Eclipse on Windows XP, and I need to get multiple processes running (this is going to be a simulation of a multi-computer system). My initial hackup used multiple threads to multiple classes, but now I'm trying to replace the threads with processes.
From my reading, I've gleaned that ProcessBuilder is the way to go. I have tried many many versions of the input you see below, but cannot for the life of me figure out how to properly use it. I am trying to run the .java files I previously created as classes (which I have modified). I eventually just made a dummy test.java to make sure my process is working properly - its only function is to print that it ran.
My code for the two files are below. Am I using ProcessBuilder correctly? Is this the correct way to read the output of my subprocess? Any help would be much appreciated.
David
Edit: The solution is to declare ProcessBuilder("java.exe","-cp","bin","Broker.test");
primary process
package Control;
import java.io.*;
import java.lang.*;
public class runSPARmatch {
/**
* #param args
*/
public static void main(String args[]) {
try {
ProcessBuilder broker = new ProcessBuilder("javac.exe","test.java","src\\Broker\\");
Process runBroker = broker.start();
Reader reader = new InputStreamReader(runBroker.getInputStream());
int ch;
while((ch = reader.read())!= -1)
System.out.println((char)ch);
reader.close();
runBroker.waitFor();
System.out.println("Program complete");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
subprocess
package Broker;
public class test {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("This works");
}
}
You are calling the java compiler on the .java file, this will not run the class. What you probably want to do is running java.exe on your .class file. (ie something like "java.exe -cp ./bin Broker.test", assuming your class files are in ./bin)

Categories

Resources