org.hibernate.HibernateException: Not able to obtain connection - java

I'm getting this exception when trying to create SQL query.
I'm trying use session in thread's run() method.
Hibernate exception org.hibernate.HibernateException: Not able to obtain connection
at org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:113)
at org.hibernate.jdbc.AbstractBatcher.prepareQueryStatement(AbstractBatcher.java:88)
at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1162)
at org.hibernate.loader.Loader.doQuery(Loader.java:390)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:218)
at org.hibernate.loader.Loader.doList(Loader.java:1593)
at org.hibernate.loader.Loader.list(Loader.java:1577)
at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:112)
at org.hibernate.impl.SessionImpl.listCustomQuery(SessionImpl.java:1414)
at org.hibernate.impl.SQLQueryImpl.list(SQLQueryImpl.java:153)

Manual memory management is not available in Java. The object will automatically become eligible to be recycled when it goes out of scope. What is holding onto your object? There must be a class, or another object referencing it for it not to be recycled by the GC.

A core concept of Java is that you have no control (which also means that you should not care) when Objects are removed from the RAM.
Generally, the Garbace-Collector will pick up an Object that is no longer referenced to by anything. WHen exactly this happens is not exactly predictable though.
So in short: You can not do that. Objects that stay in the RAM though are still referenced by something.

I would refer to this article: When does System.gc() do anything
You can actually try and call the Garbage Collector but Java is a stubborn animal and will only actually collect garbage when it feels the garbage needs to be collected.

In Java, an object will be shortlisted for garbage collection when is no longer possible to be reached from any active reference.
You can facilitate this by assigning its reference to null:
obectRef = null;
But, this is no guarantee that it will actually be deleted.

Related

Is there a way to receive object, without having reference to it?

Suppose following code:
Object obj = new Object();
obj = null;
At this point, i don't have any reference to this object, but it's still on the heap, because garbage collection don't happens instantly. Is there a way to re obtain reference on this object, before it'll be collected by GC?
Only possible way that i seen so far is to use Unsafe, which provides direct memory access, but i will need to know where in memory exactly object is allocated. Also, there is Weak\SoftReference, but they are implemented by special GC behavior.
P.S. To predict questions like "Why do you need it?" - Because science is not about why, it's about why not! (c)
This is highly JVM implementation specific. In a naive implementation having memory allocation information associated with each object, you could find an object whose memory has not been freed yet and it seems you are thinking into that direction.
However, sophisticated JVMs don’t work that way. Associating allocation information with each object would create a giant overhead, given that you may have millions of objects in your runtime. Not only regarding memory requirement, but also regarding the amount of work that has to be done for maintaining these information when allocating or freeing an object.
So what makes a part of your heap memory an object? Only the reference you are holding to it. The garbage collector traverses existing references and within the objects found this way, it will find meta information (i.e. a pointer to class specific information) needed to understand how much memory belongs to the object and how to interpret the contained data (to traverse the sub-references, if any). Everything unreferenced is unused per se and might contain old objects or might have never been used at all, who knows. Once all references to an object are gone, there is no information left about the former existence of this object.
Getting to the point, there is no explicit freeing action. When the garbage collector has found surviving objects, they will be copied to a dedicated new place and their old place is considered to be free, regardless of how many objects there were before and how much memory each individual object occupied when it was alive.
When you search memory that is considered to be unused, you may find reminiscences of old objects, but without references to their starting points, it’s impossible to say whether the bit pattern that looks like an object really is a dead object or just a coincidence. Even if you managed to resurrect an object that way, it had nothing to do with your original idea of being able to resurrect a reference, because the gc didn’t run yet.
Note that all modifications to this ordinary life time work by holding another reference to the object. E.g., when the class defines a non-trivial finalize() method, the JVM has to add a reference to the queue of objects needing finalization. Similarly, soft, weak and phantom references encapsulate a reference to the object in question. Also a debugger may keep a reference to an object, once it has seen it.
But for your trivial code Object obj = new Object(); obj = null;, assuming there’s no breakpoint set in-between, there will be no additional reference and hence, no way of resurrecting the object. A JVM may even elide the entire allocation when optimizing the code at runtime. So then you wouldn’t even find remainings of the object in the RAM when searching it as the object effectively never existed.
At this point, i don't have any reference to this object, but it's still on the heap, because garbage collection don't happens instantly.
It is undefined where it is, and it is also undefined whether or not garbage collection happens instantly.
Is there a way to re obtain reference on this object, before it'll be collected by GC?
You already had one and you threw it away. Just keep it.
I will need to know where in memory exactly object is allocated.
There is nothing in standard Java that will tell you that, and no useful way you could make use of the information if you could get it.
Also, there is Weak/SoftReference, but they are implemented by special GC behavior.
I don't see how this affects your question, whatever it is.

why nullify instance variables when destroying a stateful EJB?

In an example of the #remove annotation on a stateful EJB, the annotated method nullifys the bean's instance variables. Why? Surely destroying the bean destroys its contents, i.e. any variables?
Thanks,
Jon
Setting all fields of an object to null has two useful effects:
It provides a hard barrier against logic errors that would lead to an invalid object being reused. The application would crash instead of silently producing incorrect results.
It helps the Java VM garbage collector by removing edges from the object reference graph, thus improving the overall performance.
Can you post the example source code? Or don't. Pro-actively setting null is not needed - when EJB is destroyed and garbage collected soon later, all objects it references (of course providing there are no other references to them) will be garbage collected as well.
If ejbRemove(), Attributes of instance are wiped clean and client still has reference to instance. Client still can access the same object. That is not desirable.

Is there any advantage to assign null to a ref when it is no longer used?

I heard that assign a reference to null explicit will help gc to collect it.
Is that true?
If an object is out of scope, will it get gc quickly?
if an object is out of scope, will it get gc quickly?
That is impossible to answer in general. However, if a reference is about to go out of scope, setting it to null just before it does will almost certainly achieve nothing.
On the other hand, if the reference variable is long-lived, then setting it to null may be useful if the referenced object is no longer needed.
Typically the JVM will do garbage collection when it needs to, so assigning a reference to null will not help it happen more quickly.
If you have an array or reference which you intend to keep it can be worth nulling it out.
If you have a long method with a large object which will not go out of scope immediately, refers to a large object it could be worth nulling it out. However in this situation, it is better the break up the method at the point where the object is no longer needed so it goes out of scope.
If that is the only reference then the GC can free the space on the heap that the object was using. However, if there is another reference to the same object then setting the first reference to null will do nothing. The second reference will still keep the object alive - so the GC will not free the space.
In general, if the reference is about to go out of scope, you don't need to explicitly null it as it will be gone soon any way.
The only explicit nulling or removing of references I consciously use are:
Closing a resource associated with an object that has a longer lifetime than that resource. For example: a java.sql.Connection implementation usually has an associated physical connection (eg a Socket): when the java.sql.Connection is closed you can null this physical connection as you are no longer using it, while the actual java.sql.Connection will (might) still be held by the user for an indefinite time. (I use this example as I am a developer of a JDBC driver, in general this example does not occur for a Java developer, but similar situations exist)
Processing relatively large 'throw-away' objects in a list or array structure. For example: the JavaMail library provides methods to get messages; these return an array of messages. If you process the messages sequentially (and then no longer need them), nulling the array-entry after processing could reduce the memory footprint of your application (with IMAP it can 'on demand' load information from the server and store it in the message, increasing its size due to processing).
There are probably some other cases I will explicitly null a reference, but that is usually to signify the unavailability of something not out of concern about garbage collection or memory usage.
However as always: don't just null because you think it could help: null if you know it will help (so profile the code, measure memory usage etc). And if it is a one off hobby application or university assignment: don't bother.

When a PhantomReference/SoftReference/WeakReference is queued, how do you know what it referred to?

I haven't used PhantomReferences. There seems to be very few good examples of real-world use.
When a phantom shows up in your queue, how do you know which object it is/was? The get() method appears to be useless. According to the JavaDoc,
Because the referent of a phantom reference is always inaccessible,
this method always returns null.
I think that unless your object is a singleton, you always want to use a subclass of PhantomReference, in which you place whatever mementos you need in order to understand what died.
Is this correct, or did I miss something?
Is this also true for SoftReferences?
For WeakReferences?
Links to relevant examples of usage would be great.
I think that unless your object is a singleton, you always want to use a subclass of PhantomReference, in which you place whatever mementos you need in order to understand what died.
You could also use a Map<Reference<?>, SomeMetadataClassOrInterface> to recover whatever metadata you need. Since ReferenceQueue<T> returns a Reference<T>, you either have to cast it to whatever subclass of PhantomReference you expect, or let a Map<> do it for you.
For what it's worth, it looks like using PhantomReferences puts some burden on you:
Unlike soft and weak references, phantom references are not automatically cleared by the garbage collector as they are enqueued. An object that is reachable via phantom references will remain so until all such references are cleared or themselves become unreachable.
so you'd have to clear() the references yourself in order for memory to be reclaimed. (why there is usefulness in having to do so vs. letting the JVM do this for you is beyond me)
Your question has caused me to look into it a little more, and I found this very well written explanation and examples of all the reference types. He even talks about some (tenuous) uses of phantom references.
http://weblogs.java.net/blog/2006/05/04/understanding-weak-references

What is Object Pooling in Java?

What is object pooling and what is a weak object reference ?
How can we implement them using Java?
An object pool is a collection of a particular object that an application will create and keep on hand for those situations where creating each instance is expensive. A good example would be a database connection or a worker thread. The pool checks instances in and out for users like books out of a library.
Usually object pooling is handled by a Java EE application server. If you need to do it yourself, best to use something like Apache's object pool. Don't write one yourself; thread safety and other issues can make it complicated.
Here's a good reference on weak object references.
Check common-pools
provides an Object-pooling API
It is generally used for objects whose creation is expensive. In order to avoid that you maintain a pool of N pre-created objects and reuse them.
A weak reference is a kind of reference variable which is treated specially by the garbage collector.
This introduces another kind of reachability, any object may be:
strongly reachable (reachable from any life thread by only normal references)
weakly reachable (not strong reachable, but reachable by a weak reference (or by multiple ways, which each include a weak reference))
not reachable at all
(There are also Soft References and Phantom References, which I leave out here - they work similarly and introduce more levels between.)
If an object is not reachable at all, it can be garbage-collected at any time.
If an object is strongly reachable, it can not be garbage-collected at all.
If the garbage collector finds that an object (or a group of objects) is weakly reachable (maybe by multiple weak references), it clears all these references at once, and then the objects are not reachable (and can be garbage-collected).
(Actually there is/may be a finalization step between the "non reachable" and the collection, which also may make the object again reachable.)
For using Weak references, you can use the class java.lang.ref.WeakReference - the actual reference is in a private variable of this class, and can only be set with the constructor, and later cleared. You can subclass this class, if you need other data apart from the reference itself, which should still be there when the reference is cleared.
For an object pool in the sense of "avoid costly instantiation", a weak reference is not the right tool.
An object pool is any collection of object which are recycled, rather than recreated each time they are needed.
There are a number of ways you can implement such an Object Pool depending on your requirements. Object pools used to help performance even for simple objects but are not as useful in Java 5+.
I suggest you only use them for objects which connection to external resources such as file, sockets or database connections.
The idea of object pool pattern is similar to that of library. Everyone of us know it is cheaper and easier to go to a library and borrow a book instead of buying it.Likewise, it is cheaper (with regards to system memory and speed) for a process to borrow an object rather then to instantiate it. So such process in which a process borrow an object from another process is termed as object pooling.
Pooling & Object Pooling:
Pooling basically means utilizing the resources efficiently, by limiting access of the objects to only the period the client requires it.
Increasing utilization through pooling usually increases system performance.
Object pooling is a way to manage access to a finite set of objects among competing clients.
In other words, object pooling is nothing but sharing of objects between different clients.
Since object pooling allows sharing of objects, the other clients/processes need not re-instantiate the object (which decreases the load time), instead they can use an existing object.
After the usage, the objects are returned to the pool.
Weak reference object:
A weak reference is a holder for a reference to an object called the referent.
With weak references, you can maintain a reference to the referent without preventing it from being garbage collected.
When the garbage collector traces the heap, if the only outstanding references to an object are weak references, the referent becomes a candidate for GC as if there were no outstanding references and any outstanding weak references are cleared.
Remember, GC always, using some algorithms, reclaim the weakly reachable objects.
I implemented a simple ObjectPool in Java, see here
It doesn't use weak object reference though. Purpose of weak object reference to allow collect an object memory even if there are references to the object, but they are weak. It is more useful for caches than for object pools, although can be used for them too.
I suspect you are trying to ask about a SoftReference cache (not WeakReference). I cannot find it right now, but I remember reading from someone who implemented a proprietary JVM begging people to not use them. His argument was that these caches suppose that the author of the garbage collector somehow knows more about your caching needs than you do (which should never be true).
What I recall seeing back in the day was that if a GC cycle did not free up enough memory, all SoftReferences subsequently got cleared at once, i.e. the cache goes from ridiculously (out of memory) full to (an equally ridiculous) totally empty. Instead, choose a cache implementation that works based on size, or age, or both, i.e. one that you can give your own sensible rules to, rather than trying to offload the decision of how your cache works to the person who wrote the garbage collector for some reason.

Categories