0

I read that when sending an object to the function/another object, not the actual object is sent, but his copy. So, when multithreading, I have a ArrayBlockingQueue with size of one, and two classes -- Producer and Consumer (which are extensions of Thread), which read and write the data, accordingly, this way:

ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>();
Producer add = new Producer(queue);
Consumer show = new Consumer(queue);

I'm not sending to the constructors the "queue" variable itself, but the copy of it. So, both of objects have different queues, so there's not going to be any misunderstanding between these two objects, right? If yes, why do we need thread synchronization? If no, why?

nicks
  • 2,161
  • 8
  • 49
  • 101
  • possible duplicate of [Is Java pass by reference?](http://stackoverflow.com/questions/40480/is-java-pass-by-reference) – Mat Apr 25 '11 at 08:44

3 Answers3

1

I read that when sending an object to the function/another object, not the actual object is sent, but his copy.

This is incorrect. Java passes by value, but it passes references by value. So a copy of the queue's reference is passed to the producer and consumer. However, the object referenced is not copied.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • So, you want to say that it actually copies some variable in memory, which contains the number representing the reference to the object? – nicks Apr 25 '11 at 08:48
  • @Nika: yes, that's what happens with Objects. Primitive types like int are just copied. – Michael Borgwardt Apr 25 '11 at 08:54
0

No, add and show both would have a reference to the same object, the ArrayBlockingQueue known as queue.

If you think about it, it wouldn't do very much good to have only copies passed around. How would actual information ever get passed around after construction time?

Since presumably add and show are in different Threads, you need a synchronization mechanism.

corsiKa
  • 81,495
  • 25
  • 153
  • 204
0

In your example, you are passing the same object to both the add and show objects. You are not passing a copy. Therefore any operations by add may have an impact on show so thread synchronisation is required in this case

pgbsl
  • 222
  • 1
  • 3