My first question here. Java self taught, not an expert.
I am having a main application creating a manager thread. Manager will create worker threads. Main will pass on "Properties" as parameter to Manager. Manager will make some additions to the properties and pass it on as parameter to each Worker.
Problem:
After instantiating the worker objects when I make a change in the properties member that is part of Manager, the properties members that are part of worker threads are also getting changed. Since properties in Worker class is a private member, I thought it can only be changed within Worker class. Why is it getting changed when I make a change in the Manager? How can I avoid this issue?
Attached a simple version of the code here:
Main.java:
import java.util.Properties;
public class Main {
public static void main(String arg[])
{
Properties properties = new Properties();
properties.put("p1", "v1");
Manager manager = new Manager(properties);
manager.start();
}
}
Manager.java:
import java.util.Properties;
public class Manager {
private Properties properties;
Manager(Properties argProperties)
{
properties = argProperties;
}
public void start()
{
properties.put("workerId", "worker1");
spawnWorker();
try {
Thread.sleep(2000);
}catch(InterruptedException ex){
//do nothing
}
System.out.println("Manager going to change worker ID to 2");
properties.put("workerId", "worker2");
spawnWorker();
try {
Thread.sleep(2000);
}catch(InterruptedException ex){
//do nothing
}
Thread manager = new Thread("manager"){
public void run() {
System.out.println("Manager going to change worker ID to haha");
while(true)
{
try {
properties.put("workerId", "hahaha");
Thread.sleep(1000);
}catch(InterruptedException ex){
//do nothing
}
}
}
};
manager.start();
}
private void spawnWorker()
{
Worker worker = new Worker(properties);
worker.start();
}
}
Worker.java:
import java.util.Properties;
public class Worker {
private final Properties properties;
String workerId;
Worker(Properties argProperties)
{
properties = argProperties;
workerId = properties.getProperty("workerId");
}
public void start()
{
Thread worker = new Thread("worker-" + workerId){
public void run() {
while(true)
{
try {
System.out.println(this.getName() + "<->" + properties.getProperty("workerId"));
Thread.sleep(1000);
}catch(InterruptedException ex){
//do nothing
}
}
}
};
worker.start();
}
}
Output:
worker-worker1<->worker1
worker-worker1<->worker1
worker-worker1<->worker1
Manager going to change worker ID to 2
worker-worker2<->worker2
worker-worker1<->worker2
worker-worker2<->worker2
worker-worker1<->worker2
Manager going to change worker ID to haha
worker-worker2<->worker2
worker-worker1<->hahaha
worker-worker2<->hahaha