I am just starting out in Java and stumbled upon multithreaded applications. I know this question is similar to some posts here, but I could not find a better answer for my request. Basically, I want to pass an object to a static method, and the method will simply return a result based on the values ββ/ properties of the object. For each call, I create a new instance of the object, and there is no chance that I will modify the object inside the method. Now, to my question, will the JVM create a new instance of the static method and its local variables on the stack (excluding the object, as it will be on the heap) for each call by multiple threads? For a clear idea of ββwhat I want to achieve, here is my code:
TestConcurrent.java
import classes.Player; public class TestConcurrent { private static int method(Player player) { int y = (player.getPoints() * 10) + 1; try { Thread.sleep(1000); } catch (InterruptedException e) {} return ++y; } public static void main(String[] args) throws Exception {
Player.java
package classes; public class Player { private int acctId, points; String firstName, lastName; public Player(int acctId, int points, String firstName, String lastName) { this.acctId = acctId; this.points = points; this.firstName = firstName; this.lastName = lastName; } public int getAcctId() { return acctId; } public void setAcctId(int acctId) { this.acctId = acctId; } public int getPoints() { return points; } public void setPoints(int points) { this.points = points; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } }
OUTPUT:
Since I did not set a synchronized keyword, the output will be different every time, and it looks something like this: (the output is correct, and this is exactly what I expect, I just want to clarify that I am in the right path, since I do not want use synchronization, as this will slow down the process, because each thread will have to wait for the completion of the other thread before it can call the static method)
Thread 2: 22 Player8 : Points=8 Name=FirstName8 LastName8 Thread 22: 222 Thread 26: 262 Thread 23: 232 Player23 : Points=23 Name=FirstName23 LastName23 Thread 21: 212 Player21 : Points=21 Name=FirstName21 LastName21 Thread 25: 252 Player25 : Points=25 Name=FirstName25 LastName25 Thread 20: 202 Thread 19: 192 Thread 24: 242 Player24 : Points=24 Name=FirstName24 LastName24 Player9 : Points=9 Name=FirstName9 LastName9 Thread 28: 282
Popoy makisig
source share