Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / August 2007

Tip: Looking for answers? Try searching our database.

one thread is created for each object construction?

Thread view: 
Steve - 23 Aug 2007 05:32 GMT
For each object construction (for example, Emp e = new Emp(); ), does
the JVM creates one thread for each object construction? Each new
created object should be stored in the heap.

please advice. thx.
Lew - 23 Aug 2007 05:55 GMT
> For each object construction (for example, Emp e = new Emp(); ), does
> the JVM creates one thread for each object construction? Each new
> created object should be stored in the heap.

No, a new thread is not created unless the programmer commands it so.

A constructor call is synchronous.  That means that the caller waits until the
constructor is finished, then control resumes with the statement or expression
in the caller immediately following the "new" call.

All this happens in the same thread - caller, constructor, and all.

Yes, the object is created in the heap.

All Java objects are created in the heap.

Signature

Lew

Twisted - 23 Aug 2007 06:35 GMT
> For each object construction (for example, Emp e = new Emp(); ), does
> the JVM creates one thread for each object construction?

Only if the object's class extends Thread. Even then the construction
runs in the thread where the "new" expression occurs. The new thread
only actually begins to run when its "start" method (inherited from
Thread) is invoked.

> Each new created object should be stored in the heap.

All Java objects live on the heap, all of the time, in any compliant
implementation, at least conceptually (meaning it won't matter to you,
the programmer, if as some sort of optimization a temporary object the
JIT compiler statically proves never has references escape the local
context is actually stored on the stack or something -- the semantics
of the language are such that all objects can be assumed to be on the
heap).

References and primitives may exist either in the heap (as fields of
an object) or the stack (local variables and parameters, including the
implicit "final" parameter "this"). If your method has local variables
int x = 3; String y = null; String z = "foo"; then it has an int and
two references on the stack while running, and a single String object
on the heap that exists from the time your class is loaded probably
until the VM exits (string literals are interned). If it also hase
Object w = new Object(); then it has a third reference on the stack,
and each time it runs it creates a new Object on the heap. This object
survives until no longer referenced and then is (not necessarily very
quickly, let alone immediately) garbage collected and goes away. Most
of the times you needn't concern yourself with when it goes away
either -- it won't until you can no longer refer to it or use it
anyway, and it will before letting your app run out of memory. The
main exceptions are:

* Objects like streams that hold resources other than memory, such as
open file handles. The file handle remains open until the object is
garbage collected, which might be a long time after it becomes
unreachable. This can result in a shortage of file handles, or worse,
a delay in writing the last data out to a file. If a user saves their
work and continues editing, then the power goes out, and the stream
used to save their work is still pending garbage collection, the last
piece of the file could be missing when the power comes back on, which
is very, very bad. Uncollected, still-open streams can also cause
stale locks on some filesystems (*cough*Windows*cough*). All objects
that hold resources or have some kind of flush or other "finished with
this" capability should have this done when no longer in use. They
need to be treated as if they were locals, even though they
technically live on the heap: one method running in one thread "owns"
the resource and calls its close, dispose, flush, or whatever method
when done with it. Using try ... finally is strongly recommended to
ensure this is done even if an exception is thrown. Streams and GUI
objects are the only example of this you're likely to encounter either
early in your Java career or regularly. (Creating a new JDialog
repeatedly and never disposing the old ones will leak window handles
on lots of systems. Recycling a single instance will prevent this, as
will disposing each instance after it's closed.) The below other
exceptions about GC timing not affecting program or system behavior
also tend to arise only in more obscure and advanced situations; the
last one is specific to particular, uncommon types of application in
particular deployment circumstances but this next one is encountered
occasionally in general-purpose Java programming.

* Reference objects (java.lang.ref.FooReference) -- the referent can
go away if not referenced in any other way, causing get to return
null. Normally you use this when you specifically don't want to have a
"grip" on the object but just a reference you can use while it still
lives. This includes the keys in WeakHashMap too -- the map's
remaining in use won't stop the key being reclaimed if it's no longer
in use, and the value might then become reclaimable too by no longer
being reachable. This lets you have a mapping associate an object with
a value and still let that object be freed from memory; once it's gone
you can no longer use the mapping anyway so it can go away. (This is
only true for objects that use the default equals and hashCode; value-
type objects should not be used in a WeakHashMap as keys lest the
specific instance used as the key disappear and take the mapping with
it, while other, equal instances remain as possible arguments to the
map's get method, or at least might be constructed in the future.)

* Some high-performance and real-time VM options ensure a responsive
application by limiting the time spent in GC. If objects are created
too rapidly these can run out of memory with dead objects still on the
heap. This is rather silly though -- a full, however-slow emergency GC
hiccuping the app's performance would be vastly preferable to its
outright crashing. Nonetheless some obscure and rarely used VM options
can produce this behavior.
Ishwor Gurung - 23 Aug 2007 09:07 GMT
>> For each object construction (for example, Emp e = new Emp(); ), does
>> the JVM creates one thread for each object construction?
[quoted text clipped - 3 lines]
> only actually begins to run when its "start" method (inherited from
> Thread) is invoked.

Hey hi,
doesn't thread get created ? in the JVM ? AFAIK, JVM is one big process
(running as java/java.exe) but the fragments that we initialise, i.e., in
OPs case, the object "e". Isn't it a thread in JVM? it def can't be a
process. ??? any ideas?
Let me sort of rephrase my question, javac/javac.exe creates one big chunk
of bytecode, JVM reads line by line of that bytecode and instantiates as
per the lines in the code. Now, if if it was a process, we would surely see
it when we do "ps -ef". But we dont!. we see it as "java <something>"
instead. so how does that explain things ?

thanks a lot!

Signature

Cheers,
Ishwor Gurung
/* humpty dumpty */

Lew - 23 Aug 2007 13:51 GMT
Steve wrote:
>>> For each object construction (for example, Emp e = new Emp(); ), does
>>> the JVM creates one thread for each object construction?

Twisted wrote:
>> Only if the object's class extends Thread. Even then the construction
>> runs in the thread where the "new" expression occurs. The new thread
>> only actually begins to run when its "start" method (inherited from
>> Thread) is invoked.

> doesn't thread get created ? in the JVM ? AFAIK, JVM is one big process

We have a contexzt mismatch here.

Twisted was referring to threads spawned by application code.  Ishwor seems to
be talking about threads managed internally by the JVM, such as the garbage
collector (GC) thread.

Threads do get created in the JVM, but the ones of interest are the
application threads, of which there is only one until the programmer decides
otherwise.

> (running as java/java.exe) but the fragments that we initialise, i.e., in
> OPs case, the object "e". Isn't it a thread in JVM? it def can't be a
> process. ??? any ideas?

No, construction does not spawn a new thread.

> Let me sort of rephrase my question, javac/javac.exe creates one big chunk
> of bytecode, JVM reads line by line of that bytecode and instantiates as
> per the lines in the code. Now, if if it was a process, we would surely see
> it when we do "ps -ef". But we dont!. we see it as "java <something>"
> instead. so how does that explain things ?

The application is not a process to the OS (usually), but java is.  That
doesn't mean it's automatically multithreaded, other than the GC thread.

Whatever threads a Java application has, including the one main thread, are
part of the "java" process.  That is correct.

It doesn't explain anything regarding the OP's question.

The OP had asked if constructing an object spawned a new thread.  It does not.

Signature

Lew

Ishwor Gurung - 23 Aug 2007 17:12 GMT
........

> Twisted was referring to threads spawned by application code.  Ishwor
> seems to be talking about threads managed internally by the JVM, such as
> the garbage collector (GC) thread.

Yeah.tongue-in-cheek. :-?

> Threads do get created in the JVM, but the ones of interest are the
> application threads, of which there is only one until the programmer
> decides otherwise.

Yes agreed.

>> (running as java/java.exe) but the fragments that we initialise, i.e., in
>> OPs case, the object "e". Isn't it a thread in JVM? it def can't be a
>> process. ??? any ideas?
>
> No, construction does not spawn a new thread.

Loosing some foundation here... Internally in the JVM, how is the object "e"
represented? It'll well be an instance of a class in the heap but that's
not what I intended to ask. Apologies. What I wanted to ask (without
forking a seperate discussion thread :-) was how threading works at JVM
level.

>> Let me sort of rephrase my question, javac/javac.exe creates one big
>> chunk of bytecode, JVM reads line by line of that bytecode and
[quoted text clipped - 4 lines]
> The application is not a process to the OS (usually), but java is.  That
> doesn't mean it's automatically multithreaded, other than the GC thread.

Yes, java will look like any other process to the OS. But how are different
_instances_ of different non-related class represented in JVM? This seems
to point me to the assumption, that the classes are indeed executing as
threads in JVM.

> Whatever threads a Java application has, including the one main thread,
> are
> part of the "java" process.  That is correct.

Yup.

> It doesn't explain anything regarding the OP's question.

I didn't. As I mentioned above, I wanted to ask a question without forking a
seperate discussion thread. Apologies for hijacking the thread.

> The OP had asked if constructing an object spawned a new thread.  It does
> not.

Yes, but how about in the JVM? Is there a tutorial on how JVM works
somewhere? Perhaps tucked neatly instead of Sun's
lengthy-full-of-mathematical-symbol ones? :P

Thanks!

Signature

Cheers,
Ishwor Gurung
/* humpty dumpty */

Lew - 23 Aug 2007 18:54 GMT
Lew wrote:

> Loosing some foundation here... Internally in the JVM, how is the object "e"
> represented? It'll well be an instance of a class in the heap but that's
> not what I intended to ask. Apologies. What I wanted to ask (without
> forking a seperate discussion thread :-) was how threading works at JVM
> level.

Threading works by spawning a new OS thread and executing code in that thread.

The object "e" is represented by a data structure on the heap.  It has nothing
to do with threading.  There is bytecode at a location in the JVM that
represents the data and methods of the object.

> Yes, java will look like any other process to the OS. But how are different
> _instances_ of different non-related class represented in JVM? This seems
> to point me to the assumption, that the classes are indeed executing as
> threads in JVM.

They aren't.  Different instances are represented as separate collections of
data on the heap.

>> The OP had asked if constructing an object spawned a new thread.  It does
>> not.
>
> Yes, but how about in the JVM? Is there a tutorial on how JVM works
> somewhere? Perhaps tucked neatly instead of Sun's
> lengthy-full-of-mathematical-symbol ones? :P

I don't understand what you're asking, really.  Construction of an object does
not spawn a new thread, not in the JVM, not anywhere, not nohow.  (Of course,
it is possible that someone somewhere might write a JVM that violates this,
but it doesn't change the conceptual model.  Anyhow, no JVM I've heard of does
violate this.)

Threads and construction are orthogonal concepts.

I don't know about tutorials about specific JVM implementations.  There are
several JVMs out there.  The JLS defines precisely how it must behave, though.

I really think I am not understanding your question.  I am confused by how
people keep talking about constructors and threads in the same breath.  What
are you actually asking?

Signature

Lew

Joshua Cranmer - 23 Aug 2007 19:10 GMT
> I don't know about tutorials about specific JVM implementations.  There
> are several JVMs out there.  The JLS defines precisely how it must
> behave, though.

Actually, the Virtual Machine Specification defines precisely how JVMs
must behave. The JLS only defines how Java code must behave.

Signature

Beware of bugs in the above code; I have only proved it correct, not
tried it. -- Donald E. Knuth

Mark Space - 23 Aug 2007 19:17 GMT
> Loosing some foundation here... Internally in the JVM, how is the object "e"
> represented?

Google will help you here.  Here's one page I found doing a search for
"java threads internals":

http://www.artima.com/insidejvm/ed2/jvm6.html

> It'll well be an instance of a class in the heap but that's
> not what I intended to ask. Apologies. What I wanted to ask (without
> forking a seperate discussion thread :-) was how threading works at JVM
> level.

There's no one way for all JVMs to implement threading.  Sun left the
specification vague so that each platform can implement threads as it
sees fit.

Some hints here:

http://www.artima.com/insidejvm/ed2/jvm11.html

You should make and refine your own Google searches if you need more
information.

> Yes, java will look like any other process to the OS. But how are different
> _instances_ of different non-related class represented in JVM?

Bytes on the heap; sometimes bytes on the stack.

> This seems
> to point me to the assumption, that the classes are indeed executing as
> threads in JVM.

No.  Never.  You seem to have a grave misunderstanding of JVMs and maybe
programming in general.

> Yes, but how about in the JVM? Is there a tutorial on how JVM works
> somewhere? Perhaps tucked neatly instead of Sun's
> lengthy-full-of-mathematical-symbol ones? :P

Google is your friend.

http://www.google.com/search?q=java+threads+internals
Roedy Green - 23 Aug 2007 23:44 GMT
On Thu, 23 Aug 2007 18:17:22 GMT, Mark Space
<markspace@sbc.global.net> wrote, quoted or indirectly quoted someone
who said :

>There's no one way for all JVMs to implement threading.  Sun left the
>specification vague so that each platform can implement threads as it
>sees fit.

Usually Threads map onto OS threads, but sometimes threads are faked
splitting one OS thread into several Java threads.   The second
approach has lower overhead per thread, but does not allow
simultaneous execution in a dual CPU.

see http://mindprod.com/jgloss/thread.html#GREEN
Signature

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com

Ishwor Gurung - 24 Aug 2007 04:05 GMT
Hi Mark,

> http://www.artima.com/insidejvm/ed2/jvm6.html

one was indeed helpful.

......

> Some hints here:
>
> http://www.artima.com/insidejvm/ed2/jvm11.html

I found this http://www.artima.com/insidejvm/ed2/jvm2.html very helpful as
well :)

........

> http://www.google.com/search?q=java+threads+internals

Above result was using this query.

Also a very helpful one i found was by Bill Venners -
http://www.artima.com/insidejvm/ed2/jvm.html

Thanks a lot guys.

Signature

Cheers,
Ishwor Gurung
/* humpty dumpty */

Ishwor Gurung - 24 Aug 2007 04:08 GMT
.....

>> Some hints here:
>>
>> http://www.artima.com/insidejvm/ed2/jvm11.html
>
> I found this http://www.artima.com/insidejvm/ed2/jvm2.html very helpful as

....

> Also a very helpful one i found was by Bill Venners -
                                        ^^^^^^^^^^^^
       Same guy who wrote http://www.artima.com/insidejvm/ed2/jvm11.html

Signature

Cheers,
Ishwor Gurung
/* humpty dumpty */

Roedy Green - 23 Aug 2007 23:39 GMT
>For each object construction (for example, Emp e = new Emp(); ), does
>the JVM creates one thread for each object construction? Each new
>created object should be stored in the heap.

no. The only time a new thread happens in when you say, or indirectly
say, new Thread().start().

Each object you create goes nominally on the heap, though the Jet
compiler sometimes optimises and puts them on the stack. This is
transparent to you.

Signature

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2009 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.