What happens if I instantiate an object within its own constructor? - object

//object class
public class test
{
public test()
{
test t1 = new test();
}
}
//client class in same folder
public class Client
{
public static void main(String[] args)
{
test t = new test();
}
}
Does this just make infinite empty test objects?
What happens to the computer memory space/RAM do things just get deleted as more objects are continuously created?

Your initial reasoning is correct: you get an "infinite" number of test objects. Each object creates a new one. The constructor for the first object created (by main) never finishes.
However, the Java Virtual Machine (JVM) has a limit on the stack size. Every time the constructor calls the next constructor, an entry is pushed onto the stack. Within a short amount of time, you'll get a stack overflow exception and your program will be terminated.

Related

DoCallBack CrossAppDomainDelegate behavior for non-static delegates

Please consider the following piece of code:
// Create a new application domain
AppDomain ad = AppDomain.CreateDomain("New domain");
Worker work = new Worker();
// if Worker class is marked as 'MarshalByRefObject', this will run in current
// appdomain.
// if Worker class is NOT marked as 'MarshalByRefObject' and is marked as
// 'Serializable', this will run in a new appdomain.
ad.DoCallBack(work.PrintDomain);
// or ad.DoCallBack(new CrossAppDomainDelegate(work.PrintDomain));
// But for static methods:
// If ppp method is static, no marking is required and it will run in
// a new AppDomain.
ad.DoCallBack(Worker.ppp);
How do we explain this behavior of DoCallBack?
Why is the non-static method PrintDomain executed in the current domain when the Worker class is marked MarshalByRefObject?
Why is the non-static method PrintDomain executed in a new AppDomain when the Worker class is marked Serializable?
Why doesn't the static method need any markings?
Why is the non-static method PrintDomain executed in the current domain when the Worker class is marked MarshalByRefObject?
Because that's what MBRO does, it creates a proxy for the object that you created in your primary appdomain. Which marshals the call from the secondary appdomain to the appdomain that owns the object, the primary appdomain.
Why is the non-static method PrintDomain executed in a new AppDomain when the Worker class is marked Serializable?
Because that scenario does not use a proxy. The object itself is marshaled from the primary to the secondary appdomain. Possible because you marked it [Serializable]. The call therefore executes in the secondary appdomain.
Why doesn't the static method need any markings?
It is unclear what you mean by "markings", but it isn't any different for a static method. Some code to play with, remove the comment on the base class to compare the two scenarios:
using System;
class Program {
static void Main(string[] args) {
var dom = AppDomain.CreateDomain("Test");
var obj = new WorkerMbro();
dom.DoCallBack(obj.PrintDomain);
dom.DoCallBack(obj.PrintDomainStatic);
Console.ReadLine();
}
}
[Serializable]
class WorkerMbro /* : MarshalByRefObject */ {
public void PrintDomain() {
Console.WriteLine(AppDomain.CurrentDomain.FriendlyName);
}
public void PrintDomainStatic() {
Console.WriteLine(AppDomain.CurrentDomain.FriendlyName);
}
}
Output as posted:
Test
Test
Output with the comments removed so the proxy is used:
ConsoleApplication1.vshost.exe
ConsoleApplication1.vshost.exe

Custom ClassLoader not garbage collected

In an attempt to solve this problem, I built a (very) small project that is reproducing part of it. It is a NetBeans project using Glassfish v2.1.1 and OpenJpa-1.2.2.
Globally, the goal is to be able to reload dynamically some business code (called 'tasks') without the need to (re)make a full deployment (eg via asadmin). In the project there are two of them: PersonTask and AddressTask which are simply accessing some data and printing them out.
In order to do that, I've implemented a custom class loader that read the binary of class files and inject it via the defineClass method. Basically, this CustomClassLoader is a singleton and is implemented like this:
public class CustomClassLoader extends ClassLoader {
private static CustomClassLoader instance;
private static int staticId = 0;
private int id; //for debugging in VisualVM
private long threadId; //for debugging in VisualVM
private CustomClassLoader(ClassLoader parent) {
super(parent);
threadId = Thread.currentThread().getId();
id = staticId;
++staticId;
}
private static CustomClassLoader getNewInstance() {
if (instance!=null) {
CustomClassLoader ccl = instance;
instance = null;
PCRegistry.deRegister(ccl); //https://issues.apache.org/jira/browse/GERONIMO-3326
ResourceBundle.clearCache(ccl); //found some references in there while using Eclipse Memory Analyzer Tool
Introspector.flushCaches(); //http://java.jiderhamn.se/category/classloader-leaks/
System.runFinalization();
System.gc();
}
ClassLoader parent = Thread.currentThread().getContextClassLoader();
instance = new CustomClassLoader(parent);
return instance;
}
//...
}
//this class is included in the EAR like a normal class
public abstract class AbstractTask {
protected Database database; /* wrapper around the EntityManager, filled when instance is created */
public abstract void process(Integer id);
}
//this one is dynamically loaded by the CustomClassLoader
public class PersonTask extends AbstractTask {
#Override
public void process(Integer id) {
//keep it empty for now
}
}
In my EJB facade (EntryPointBean), I simply do a lookup of the class, create a new instance of it and call the process method on it. The code in the project is slightly different, but the idea is quite the same:
CustomClassLoader loader = CustomClassLoader.getNewInstance();
Class<?> clazz = loader.loadClass("ch.leak.tasks.PersonTask");
Object instance = clazz.newInstance();
AbstractTask task = (AbstractTask)instance;
/* inject a new Database instance into the task */
task.process(...);
Until now, all is fine. If this code is run many times (via ch.leak.test.Test), there will be only one single instance of the CustomClassLoader when a heap analysis is done, meaning the previous instances have been successfully collected.
Now, here is the line triggering a leak:
public class PersonTask extends AbstractTask {
#Override
public void process(Integer id) {
Person p = database.getEntity("SELECT p FROM Person p WHERE p.personpk.idpk=?1", new Long(id));
//...
}
}
This simple access to the database has a strange consequence: the first time the code is run, the CustomClassLoader being used will never be garbage collected (even without any GC roots). However, all the further CustomClassLoader created won't leak.
As we can see in the dump below (done with VisualVM), the CustomClassLoader with instance id 0 is never garbage collected...
Finally, one other thing I've seen when exploring the heap dump: my entities are declared twice in the PermGen and half of them have no instances and also no GC root (but they are not linked to the CustomClassLoader).
It seems that OpenJPA has something to do with those leaks... but I don't know where I can search for more information of what I'm doing wrong. I have also put the heap dump directly in the zip with the project.
Does anyone have an idea ?
Thanks !

C# set clipboard data from class

i have a public class , in that class i have a void which sets Clipboard.Text and i have a thread from which i call that func, everytime i call it i get
Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it.
I have tried the following :
Thread t = new Thread(Worker);
t.SetApartmentState(ApartmentState.STA);
t.Start();
But i still recieve error, i even tried [STAThread]
My function looks like this
public void Set(string s)
{
Clipboard.SetText(s);
}
I believe it is telling you put put the STAThread attribute on your main function, like so:
[STAThread]
static void Main()
{
// Your code
}
You said you tried STAThread, but was it on the main function or the function you're calling?

java:singleton, static variable and thread safety

class MyClass
{
private static MyClass obj;
public static MyClass getInstance()
{
if(obj==null)
{
obj = new MyClass();
}
return obj;
}
In the above java code sample, because obj is a static variable inside the class,
will getInstance still be non-thread safe? Because static variables are shared by all threads, 2 simultaneous threads shall be using the same object. Isnt it?
Vipul Shah
Because static variables are so widely shared they are extremely un-thread safe.
Consider what happens if two threads call your getInstance at the same time. Both threads will be looking at the shared static obj and both threads will see that obj is null in the if check. Both threads will then create a new obj.
You may think: "hey, it is thread safe since obj will only ever have one value, even if it is initialized multiple times." There are several problems with that statement. In our previous example, the callers of getInstance will both get their own obj back. If both callers keep their references to obj then you will have multiple instances of your singleton being used.
Even if the callers in our previous example just did: MyClass.getInstance(); and didn't save a reference to what MyClass.getInstance(); returned, you can still end up getting different instances back from getInstance on those threads. You can even get into the condition where new instances of obj are created even when the calls to getInstance do not happen concurrently!
I know my last claim seems counter-intuitive since the last assignment to obj would seem to be the only value that could be returned from future calls to MyClass.getInstance(). You need to remember, however, that each thread in the JVM has its own local cache of main memory. If two threads call getInstance, their local caches could have different values assigned to obj and future calls to getInstance from those threads will return what is in their caches.
The simplest way to make sure that getInstance thread safe would be to make the method synchronized. This will ensure that
Two threads can not enter getInstance at the same time
Threads trying to use obj will never get a stale value of obj from their cache
Don't try to get clever and use double checked locking:
http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html
Good explanation can be found here:
http://en.wikipedia.org/wiki/Singleton_pattern
The wiki article highlights various thread-safe approaches along with some of their pros and cons.
in this case getInstance() is not thread-safe, even if you use static variable. only synchronization makes this thread-safe.
The following example shows a weird thread save modified single ton pattern which supports generics as well.
To have it just thread save and synchronization save just take the synchronized block and the transient and volatile keywords.
Notice, that there is a double check, the synchronized block is inside an if. This brings more performance, because synchronized is expensive.
Of course for a real singleton do not use maps, I said it is a modified one.
public class Edge<T> {
#SuppressWarnings({"unchecked"})
private static transient volatile HashMap<Object,HashMap<Object, Edge>> instances = new HashMap<Object, HashMap<Object,Edge>>();
/**
* This function is used to get an Edge instance
* #param <T> Datatype of the nodes.
* #param node1, the source node
* #param node2, the destination node
* #return the edge of the two nodes.
*/
#SuppressWarnings({"unchecked"})
public static <T> Edge<T> getInstance(T node1, T node2){
if(!(instances.containsKey(node1) && instances.get(node1).containsKey(node2))){
synchronized (Edge.class) {
if(!(instances.containsKey(node1) && instances.get(node1).containsKey(node2))){
Edge<T> edge = new Edge<T>(node1, node2);
if(!instances.containsKey(node1)){
instances.put(node1, new HashMap<Object, Edge>());
}
instances.get(node1).put(node2, edge);
}
}
}
return (Edge<T>)instances.get(node1).get(node2);
}
public class Singleton{
private static transient volatile Singleton instance;
public static Singleton getInstance(){
if(instance==null)synchronized(Singleton.class){
if(instance==null){
instance = new Singleton();
}
}
return instance;
}
private Singleton(){
/*....*/
}
}
Page 182:
http://books.google.com/books?id=GGpXN9SMELMC&printsec=frontcover&dq=design+patterns&hl=de&ei=EFGCTbyaIozKswbHyaiCAw&sa=X&oi=book_result&ct=result&resnum=2&ved=0CDMQ6AEwAQ#v=onepage&q&f=false
Think this can be tagged as answered now.
class MyClass
{
private static MyClass obj;
private MyClass(){
// your initialization code
}
public static synchronized MyClass getInstance()
{
if(obj==null)
{
obj = new MyClass();
}
return obj;
}
I'll agree with #Manoj.
I believe the above will be one of the best methods to achieve singleton object.
And synchronization makes the object thread safe.
Even, it's static :)

Threading from within a class with static and non-static methods

Let's say I have
class classA {
void someMethod()
{
Thread a = new Thread(threadMethod);
Thread b = new Thread(threadMethod);
a.Start();
b.Start();
a.Join();
b.Join();
}
void threadMethod()
{
int a = 0;
a++;
Console.Writeline(a);
}
}
class classB {
void someMethod()
{
Thread a = new Thread(threadMethod);
Thread b = new Thread(threadMethod);
a.Start();
b.Start();
a.Join();
b.Join();
}
static void threadMethod()
{
int a = 0;
a++;
Console.Writeline(a);
}
}
Assuming that in classA and classB, the contents of threadMethod have no effect to anything outside of its inner scope, does making threadMethod in classB static have any functional difference?
Also, I start two threads that use the same method in the same class. Does each method get its own stack and they are isolated from one another in both classA and classB?
Does again the static really change nothing in this case?
Methods don't have stacks, threads do. In your example threadMethod only uses local variables which are always private to the thread executing the method. It doesn't make any difference if the method is static or not as the method isn't sharing any data.
In this case there is no functional difference. Each thread gets it's own stack
Maybe you can be a little more clear. It doesn't matter if the function is declared static or not in most languages. Each thread has its own private statck.
Each thread would get it's own stack. There is no functional difference that I can tell between the two.
The only difference (obviously) is that the static version would be unable to access member functions/variables.

Resources