开发者

How to enforce that every object has its own state in multi-threaded environment? (Java)

开发者 https://www.devze.com 2023-02-06 14:43 出处:网络
Example of 3 classes that I have (Start is the class with main()): class A{ protected Map<String, String> map;

Example of 3 classes that I have (Start is the class with main()):

class A{

protected Map<String, String> map;

public A(File input){
 map = new HashMap<String, String>();
 updateMap(input);
}

private void updateMap(File input){..}

}


class Start{

private MultiThreadedClass newThread;
...
for(int i=0;i< numOfThreads; i++)
 newThread = MultiThreadedClass(file[i]);
 newThread.start();
}


class MultiThreadedClass extends Thread{
...
 public void run(){
    A a = new A(file);
 }
}

Here's my question - Every thread is given a different file and its job is to execute the updateMap method and update the map according to the file. The map must contain only values from one file. Does the given imple开发者_开发问答mentation enforce that? when Implementing this my idea was that the new A() call for every thread would guarantee that every thread has its own map and even if two threads update the map at the same time, each only updates its own copy. But I'm not sure if this is correct.

Thank you!


Your hunch is correct. Each time you call "new ClassName", space is allocated in memory for an object of the ClassName you specified. The only way other threads would be able to access this memory is if you make it available, either by passing it as a parameter to another function, assigning its reference to public member variable of your thread class, or returning it from a public member function of your thread class (after assigning it to a member field of your class).

Since you've created the object locally in the run function, and you're not keeping any references to an A class as a member of your Thread class, the only way someone else could get ahold of the A object is if you pass it as a parameter to another method, and that method did something to hold onto the value.

When the run function completes and execution exits that method, the A object will cease to exist, as will the Map you've created inside of the A object.


Helps to know the terminology. There is a way to define so called 'thread-local' variables. Please see this Java doc for information:

http://download.oracle.com/javase/1.4.2/docs/api/java/lang/ThreadLocal.html

0

精彩评论

暂无评论...
验证码 换一张
取 消