1

I have been reading, and I found out that no matter, where object is created on code e.g. as member variable, local variable or class variable, they are always created inside heap space in Java. I'm wondering if in this example the ArrayList created when executing doSomething(), will be shared between threads generating concurrency problems, or two different instances are created in the heap.

public ArrayList<T> doSomething(){
    ArrayList<T> list = new ArrayList<>();
    //...Add content to the list
    return list;
}

public void printList(ArrayList<T> list){
    for(T element: list)
        System.out.println(element);
}

Thread thread1 = new Thread(new Runnable{
      public void run(){
           printList(doSomething());
      }
}

Thread thread2 = new Thread(new Runnable{
      public void run(){
           printList(doSomething());
      }
}

thread1.start();
thread2.start();
albusshin
  • 3,930
  • 3
  • 29
  • 57
Nicolas
  • 25
  • 3
  • To know difference between local global and static variable [ Click here][1] [1]: http://stackoverflow.com/questions/13415321/difference-between-static-auto-global-and-local-variable-in-context-of-c-and-c – Sunil Singh Bora Dec 12 '13 at 15:05

3 Answers3

5

In this piece of code here

public ArrayList<T> doSomething(){
    ArrayList<T> list = new ArrayList<>();
    //...Add content to the list
    return list;
}

and

thread1.start();
thread2.start();

You have created two ArrayLists, thus there won't be any "sharing" between the two threads, because they are totally two different objects.

albusshin
  • 3,930
  • 3
  • 29
  • 57
1

In the code you have posted, two different instances of ArrayList are created. So you are in fact dealing with two separate object instances.

But, if you were to share an instance between threads, you need to take care of thread safety.

Nishan
  • 2,821
  • 4
  • 27
  • 36
1

where object is created on code e.g. as member variable, local variable or class variable, they are always created inside heap space in Java

@Albus' answer is correct. However to add some detail, all objects are created on the heap, however, in your case:

public ArrayList<T> doSomething() {
    ArrayList<T> list = new ArrayList<>();
    ...

The reference to the object list is only stored on the stack. The ArrayList object itself is on the heap but because list is on the stack, there is no possibility for different threads to access this list which would create concurrency problems. If the two threads had access somehow to the same ArrayList object, either because it was a static field that they shared or it was passed in, then you need to worry about synchronization and concurrency.

Gray
  • 115,027
  • 24
  • 293
  • 354