Java object pointer with multiple threads

I have two threads. One thread has an instance of myObjectManager. myObjectManager has a list of objects and a method for retrieving an object (public myObjectClass getObjectById (int ID))

I need the first thread to render the object in the list of myObjectManager objects, and the second thread to execute the game logic and move it around, etc.

Here is what I tried

//thread 1:
m = myObjectManager.getObjectById(100);
m.render();

//thread 2:
m = myObjectManager.getObjectById(100);
m.rotate( m.getRotation() + 5 ); //increment rotation value

However, it seems that thread 1 has an instance of the object without an updated rotation. When I run it, the rendered object does not rotate, but when I do the second thread, print its rotation value.

In C ++, I just want the getObjectById () function to return a pointer to an instance of myObjectClass, but I'm not sure what java does when I say "return myInstance"; How do I do something like this in java?

Sorry, I'm new to this language!

+3
source share
6 answers

In Java, all object variables are "pointers" (or "references", as people usually say). The problem should be elsewhere. I assume that thread 1 already mapped the object before thread 2 even modified it.

Change . Another theory: subsequent render () operations do not actually change the screen. The rotation value is updated just fine - but it does not appear on the display.

+4
source

() , Java ( ), , - , , .

, , .

+3

, .

  • . . , threadsafe .
  •    (..    ),       .

, m. , getObjectById(), .

+2
source

Try marking your variable rotationin the object asvolatile

+1
source

All objects in Java are passed by reference.
It is impossible to write code that does what you are trying to do.

Your first thread probably works before the second thread.

0
source

All references to objects in Java , such as your variable m, are actually pointers .

So, in your example, both m variables point to the same object.

0
source

Source: https://habr.com/ru/post/1785985/


All Articles