[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

will 'count' variable be garbage collected?

Posted on 2011-05-12
22
Medium Priority
?
293 Views
Last Modified: 2012-06-21
hi guys

need some help, i want to know if 'count '  variable in below code be garbage collected?

My program structure is >>Adapter.java calls TemplateAdapter.java.
count is defined as a global variable in TemplateAdapter.java
here is the code

Adapter.java

public Workflow transformDTOToDbModel(WorkflowDTO workflowdto){
Workflow workflow = new Workflow();      
workflow.setId(workflowdto.getId());      
workflow.setTemplate(TemplateAdapter.getInstance().populateQuestionChoices(workflowdto.getQuestionChoicesDTO()));
//populate the % complete
int questionsanswered = TemplateAdapter.count;            
double percentcompl = questionsanswered / 30.0 * 100;
int  percentageComplete = percentcompl.intvalue
workflow.setPercentComplete(percentageComplete);
return workflow;
}

public class TemplateAdapter implements ITransformer<Template, TemplateDTO> {
public static int count = 0;
private static TemplateAdapter _instance;
private Logger logger = Logger.getLogger(getClass());
      
private TemplateAdapter(){}
public static TemplateAdapter getInstance(){
if(null == _instance)
_instance = new TemplateAdapter();
return _instance;
}
      

public QuestionChoices populateQuestionChoices(QuestionChoicesDTO questionChoicesDTO)
{
QuestionChoices questionChoices = new QuestionChoices();  
List<Answer> answerList = new ArrayList<Answer>();              
for (AnswerDTO answerDTO : questionChoicesDTO.getAnswers())
  {
  answerList.add(populateAnswers(answerDTO));
  }                
  questionChoices.setAnswers(answerList);              
  return questionChoices;
}      
 
public Answer populateAnswers(AnswerDTO answerDTO)
{
  Answer answer = new Answer();  
  answer.setAnswerValue(answerDTO.getDescription());
  if (answer.getAnswer() != null && answer.getAnswer().trim().length() > 0) {
count++;
  }
  return answer;
}            
      
}

Will count take a dump and cause garbage?

thanks      
0
Comment
Question by:royjayd
  • 12
  • 5
  • 5
22 Comments
 
LVL 47

Expert Comment

by:for_yan
ID: 35750678
http://stackoverflow.com/questions/453023/are-static-fields-open-for-garbage-collection


      

Static variables cannot be elected for garbage collection while the class is loaded. They can be collected when the respective class loader (that was responsible for loading this class) is itself collected for garbage.
0
 
LVL 47

Accepted Solution

by:
for_yan earned 1000 total points
ID: 35750692
count is static variable and will be garbage colleced only when the class is unloaded

Static variables are referenced by Class objects which are referenced by ClassLoaders -so unless either the ClassLoader drops the Class somehow (if that's even possible) or the ClassLoader itself becomes eligible for collection (more likely - think of unloading webapps) the static variables (or rather, the objects they reference) won't be collected.

0
 
LVL 47

Expert Comment

by:for_yan
ID: 35750701
If you use not static but instance variable, then it will be garbge collected when the instance which contains it
itself becomes eligible for garbage collection.
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 47

Expert Comment

by:for_yan
ID: 35750717
So in case of normal java application you shopuld assume that static variables will llive through the life of your application.
0
 

Author Comment

by:royjayd
ID: 35750723
Also i just realized i cannot make the above code work unless i make the populateAnswers() method static.
My second question would be how can i access the correct count so that i can
populate the % complete and at the same time i dont want count to cause garbage.

0
 
LVL 47

Expert Comment

by:for_yan
ID: 35750735

I'm not sure I understand - you can use static variables in the non-static method - it is not a problem
0
 

Author Comment

by:royjayd
ID: 35750764
>>>you can use static variables in the non-static method - it is not a problem
 i thought static variables can be used only in static methods?
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35750770
No, it is opposite: in static methods you cannot use instance varaibles
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35750773
static variables can be used everywhere even in instance of another class, just referencing this class name
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35750777
And if I were you, I would worry the least about grabge collection especuially of such thing
as one integer variable - that is jvm business and it will do it for you
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35750810
With static variables you should only worry if this class may be simpulatenousely accessed
by say differernt clients - in this case they may all share the same static variable.
If nothing like that can happen, then it is fine. If diiferent clinets access the same class, then
you should realize what it is that you are counting.
These considerations is good to have in mind and understand; they are more imporatnt than
garbage collection which will happen as it should without us needing to worry about it.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35750839
And the rule that
static methods you cannot use instance varaibles
is easy to understand - static method is not specific to any instance -
thisnk of it as just general description of some procedure - it
the result of it should denpend only on the imnput parameterts -
and you call it refreing only to the class in general, not refrring to any instance of this
class, and instance variable is pspecific to particular insatnce - makes no sense to use it
in general for the whole class static method.

And all that does not apply to your case - in the opposite situation there is no
limitation - you can uses staatic variables  in instance methods as much as you want -
you can for instance yuse them to calculate how many times this or that instance method of this
was called overall by all instances exsitinc in your applaications.
OK, this is all probably beyond your question, but it is good to realize all that,
so as you have doubtes i decided to explain.
0
 
LVL 92

Expert Comment

by:objects
ID: 35751089
Its got nothing to do with static. count is a primitive variable.
They have nothing to do with garbage collection which Objects
So no count is never going to get garbage collected
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35751113
If count is instance variable of the class it will become no longer accessible
as soon as the instance of this class is garbage collected
0
 

Author Comment

by:royjayd
ID: 35754292
primitive variables dont have to worry about garbage collection? so int/double/ other primitive data types dont have to worry about GC?

0
 
LVL 47

Expert Comment

by:for_yan
ID: 35755394
In most ordinaly programs you don't have to worry about garbage collection anyway.
That's the advantage of java, that it takes care of garbage collection for you.
This is a good subject for the question in Java classes, and maybe in some
very special cases where memory becomes an issue. In my practice don't recall
having such case in years where I had to think of garbage collection.
0
 
LVL 92

Expert Comment

by:objects
ID: 35757482
> primitive variables dont have to worry about garbage collection? so int/double/ other primitive data types dont have to worry about GC?

no, they aren't stored on the heap so theres no garbage collection to do.
The fact that the variable is static is irrelevant
0
 

Author Comment

by:royjayd
ID: 35757803
so all the primitives are stored on the stack?
thx.
0
 
LVL 92

Expert Comment

by:objects
ID: 35758661
sorry was a bit unclear with that, they are held on the heap but as a part of the containing class.
It would not however get garbage collected independently like a non-primitive variable would.
0
 

Author Comment

by:royjayd
ID: 35761305
>>>It would not however get garbage collected independently like a non-primitive variable would.
so you are saying String (non-primitive) would be garbage collected and int would not be garbage collected?
can you give an example to show what you are saying

thx

0
 
LVL 92

Assisted Solution

by:objects
objects earned 1000 total points
ID: 35762160
class X {
    String a = "abc";
    int b = 9;
}

X x = new X();
x.a = null;

// a is now available for garbage collection

x = null;

// x is now available for garbage collection
// at which time b will also get freed up
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
Suggested Courses

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question