• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Sharing of Memory in Threads?

 
vikky agrawal
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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???
 
Abimaran Kugathasan
Ranch Hand
Posts: 2066
Clojure IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Couldn't understand your question exactly. Could you elaborate a bit?
 
Paul Clapham
Sheriff
Posts: 21117
32
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 247
Chrome Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...
 
Narendra shah
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try to understand following code, where count is shared between multiple threads. Hope you get your answer.

 
vikky agrawal
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@ 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic