aspose file tools*
The moose likes Threads and Synchronization and the fly likes Sharing of Memory in Threads? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Sharing of Memory in Threads?" Watch "Sharing of Memory in Threads?" New topic
Author

Sharing of Memory in Threads?

vikky agrawal
Ranch Hand

Joined: Dec 18, 2008
Posts: 65
Using multithreading it is said that the threads shares same memory space of a process..
but if we are having a class that implements Multithreading, lets have an example:


then if we want to use multithreading then we have to create two inistances of the class..


As we are having two instances as two threads.
My question is when we create an instance of a class then one copy of all variables and methods created for that instance.
so in case of these two threads a copy will exist for all instances..
so how the process memory is shared???
as in above case
String message
variable will exist for both the instances(Threads)
So where is the sharing???


scjp 6
http://algorithmsea.blogspot.com
Abimaran Kugathasan
Ranch Hand

Joined: Nov 04, 2009
Posts: 2066

Couldn't understand your question exactly. Could you elaborate a bit?


|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18643
    
    8

It's simple. The process starts with, let's say, 300 megabytes of memory.

You create some objects. The memory for those objects comes from that 300 megabytes. Then you create some more objects. The memory for those objects also comes from that 300 megabytes. And so it goes, that 300 megabytes is shared among all the objects created by that process.

Did you think that when it said that two threads "shared" some memory, that they both got the same memory? That's not what "share" means. When you share a book with your friend, only one of you has the book at any time. Same with memory.
Ram Narayan.M
Ranch Hand

Joined: Jul 11, 2010
Posts: 247

Thread is a Light-Weight Process. So it uses the memory space of process.... At a time, Threads Context Switching takes place that is at a time, a thread can only utilize the Process memory space...


SCJP 6 [SCJP - Old is Gold]
Narendra shah
Ranch Hand

Joined: Feb 28, 2007
Posts: 51
Try to understand following code, where count is shared between multiple threads. Hope you get your answer.



Narendra Shah -- SCJP 5
vikky agrawal
Ranch Hand

Joined: Dec 18, 2008
Posts: 65
@ Narendra shah
Thanks for your post i got answer of my question.
As i was creating two different objects memory was not shared
but here in you code:

you are creating different threads.
so i got answer for my question..!
Thanks a lot.
 
 
subject: Sharing of Memory in Threads?