Stack Confinement using local object reference - java

I am following Java Concurrency in Practice, and when I read about stack confinement I felt good because it explained very well, but this statement raised some doubts for me:
Maintaining stack confinement for object references requires a little
more assistance from the programmer to ensure that the referent does
not escape
Can anyone do something in below code to produce a violation of stack confinement? I guess it has no confinement violation at present. I want to know how local object reference can violate the confinement.
/**
*
*/
package lession2.shared.object;
/**
* #author so_what
*/
class Person {
private String personName;
private String personAddress;
public String getPersonName() {
return personName;
}
public void setPersonName(String personName) {
this.personName = personName;
}
public String getPersonAddress() {
return personAddress;
}
public void setPersonAddress(String personAddress) {
this.personAddress = personAddress;
}
#Override
public String toString() {
return "Person [personName=" + personName + ", personAddress=" + personAddress + "]";
}
}
public class StackConfinement extends Thread {
public void setSomeMoreProperty() {
//this person object will be confined to each thread
Person person=new Person();
person.setPersonAddress("NY");
person.setPersonName("Xyz");
//now I wan to pass this person to the other method
doSomething(person);
System.out.println(person);
}
public void doSomething(Person person) {
person.setPersonAddress("Canada");
//can one add some thing here and violate the thread confinement
}
#Override
public void run()
{
setSomeMoreProperty();
}
public static void main(String[] args) throws InterruptedException {
StackConfinement thread1=new StackConfinement();
StackConfinement thread2=new StackConfinement();
thread1.start();
thread2.start();
thread1.join();
thread2.join();
}
}

this statement raised some doubts for me:
Maintaining stack confinement for object references requires a little
more assistance from the programmer to ensure that the referent does
not escape
Can anyone do something in below code to produce a violation of stack
confinement?
Of course. If this were not a thing then Goetz et al. would not have spent time on stack confinement in the first place.
I guess it has no confinement violation at present. I
want to know how local object reference can violate the confinement.
A reference stored in a local variable does not violate stack confinement, which the book defines as the situation in which an object can be reached only through local variables. The problem arises when there is a(nother) reference to the object that is more broadly reachable. That would happen, for example, if you store a reference to object in a static field of any class. It also happens if you store a reference to the object in a container that is not itself stack confined.
The book gives the example of a more subtle case in which a reference is stored in a container that itself is initially stack-confined, but later is published. Since the object is reachable from the (no longer stack-confined) container, it is no longer stack-confined either.
There are literally an infinity of ways in which stack-confinement violations could be introduced into your particular code, but how about this: suppose I wanted to make StackConfinement.setSomeMoreProperty() actually have a persistent effect, such as putting the Person objects it generates into a List. That would look like this:
public class StackConfinement extends Thread {
private List<Person> people = new ArrayList<>();
public void setSomeMoreProperty() {
// Initially stack-confined
Person person = new Person();
person.setPersonAddress("NY");
person.setPersonName("Xyz");
// does not break stack confinement:
doSomething(person);
System.out.println(person);
// this DOES break stack confinement:
people.add(person);
}
// ...
}
That's all well and good, but now neither the people member nor any object it references (such as the person that is added by setSomeMoreProperty()) is stack-confined.

Related

Find object created inside a method in other class

For example, 2 class: Ticket and Customer
public class Ticket{
private String cstName;
public Ticket(String name){
this.cstName = name;
}
}
public class Customer{
private String name;
public void book(){
Ticket t = new Ticket(t);
}
}
How can I find and use t object elsewhere ???
What you ask for is completely impossible. An object is made, the object is assigned to a local variable, and the method ends.
As the method ends, all local variables (and t is a local variable), immediately go into the bin and there is nothing in java that lets you 'plug into' this process or that lets you stop this process. The variable is just gone.
The object is still on the heap somewhere, but no longer accessible. Eventually it will be garbage collected. There's nothing you can do about that, either. Java does not have a 'list all objects in the heap' method and never will.
You can mess with reference queues which is an extremely advanced topic that in no way is suitable given the way this question is stated, and wouldn't work for arbitrary methods like this.
If you control the code of Ticket itself you can save the reference as part of the constructor, which would be extremely bad design, and would have nothing at all to do with the notion of t, or that the book method made it.
What you presumably want, is a field:
public class Customer {
private String name;
private Ticket ticket;
public void book() {
this.ticket = new Ticket(t);
}
public Ticket getTicket() {
return this.ticket;
}
}
and now you could do:
Customer c = new Customer();
c.book();
Ticket t = c.getTicket();
or perhaps do:
public class Customer {
private String name;
private Ticket ticket;
public Ticket book() {
this.ticket = new Ticket(t);
return this.ticket;
}
}
and now you could do:
Customer c = new Customer();
Ticket t = c.book();

Creating objects inside the Constructor [duplicate]

I know that this refers to a current object. But I do not know when I really need to use it. For example, will be there any difference if I use x instead of this.x in some of the methods? May be x will refer to a variable which is local for the considered method? I mean variable which is seen only in this method.
What about this.method()? Can I use it? Should I use it. If I just use method(), will it not be, by default, applied to the current object?
The this keyword is primarily used in three situations. The first and most common is in setter methods to disambiguate variable references. The second is when there is a need to pass the current class instance as an argument to a method of another object. The third is as a way to call alternate constructors from within a constructor.
Case 1: Using this to disambiguate variable references. In Java setter methods, we commonly pass in an argument with the same name as the private member variable we are attempting to set. We then assign the argument x to this.x. This makes it clear that you are assigning the value of the parameter "name" to the instance variable "name".
public class Foo
{
private String name;
public void setName(String name) {
this.name = name;
}
}
Case 2: Using this as an argument passed to another object.
public class Foo
{
public String useBarMethod() {
Bar theBar = new Bar();
return theBar.barMethod(this);
}
public String getName() {
return "Foo";
}
}
public class Bar
{
public void barMethod(Foo obj) {
obj.getName();
}
}
Case 3: Using this to call alternate constructors. In the comments, trinithis correctly pointed out another common use of this. When you have multiple constructors for a single class, you can use this(arg0, arg1, ...) to call another constructor of your choosing, provided you do so in the first line of your constructor.
class Foo
{
public Foo() {
this("Some default value for bar");
//optional other lines
}
public Foo(String bar) {
// Do something with bar
}
}
I have also seen this used to emphasize the fact that an instance variable is being referenced (sans the need for disambiguation), but that is a rare case in my opinion.
The second important use of this (beside hiding with a local variable as many answers already say) is when accessing an outer instance from a nested non-static class:
public class Outer {
protected int a;
public class Inner {
protected int a;
public int foo(){
return Outer.this.a;
}
public Outer getOuter(){
return Outer.this;
}
}
}
You only need to use this - and most people only use it - when there's an overlapping local variable with the same name. (Setter methods, for example.)
Of course, another good reason to use this is that it causes intellisense to pop up in IDEs :)
The only need to use the this. qualifier is when another variable within the current scope shares the same name and you want to refer to the instance member (like William describes). Apart from that, there's no difference in behavior between x and this.x.
"this" is also useful when calling one constructor from another:
public class MyClass {
public MyClass(String foo) {
this(foo, null);
}
public MyClass(String foo, String bar) {
...
}
}
There are a lot of good answers, but there is another very minor reason to put this everywhere. If you have tried opening your source codes from a normal text editor (e.g. notepad etc), using this will make it a whole lot clearer to read.
Imagine this:
public class Hello {
private String foo;
// Some 10k lines of codes
private String getStringFromSomewhere() {
// ....
}
// More codes
public class World {
private String bar;
// Another 10k lines of codes
public void doSomething() {
// More codes
foo = "FOO";
// More codes
String s = getStringFromSomewhere();
// More codes
bar = s;
}
}
}
This is very clear to read with any modern IDE, but this will be a total nightmare to read with a regular text editor.
You will struggle to find out where foo resides, until you use the editor's "find" function. Then you will scream at getStringFromSomewhere() for the same reason. Lastly, after you have forgotten what s is, that bar = s is going to give you the final blow.
Compare it to this:
public void doSomething() {
// More codes
Hello.this.foo = "FOO";
// More codes
String s = Hello.this.getStringFromSomewhere();
// More codes
this.bar = s;
}
You know foo is a variable declared in outer class Hello.
You know getStringFromSomewhere() is a method declared in outer class as well.
You know that bar belongs to World class, and s is a local variable declared in that method.
Of course, whenever you design something, you create rules. So while designing your API or project, if your rules include "if someone opens all these source codes with a notepad, he or she should shoot him/herself in the head," then you are totally fine not to do this.
this is useful in the builder pattern.
public class User {
private String firstName;
private String surname;
public User(Builder builder){
firstName = builder.firstName;
surname = builder.surname;
}
public String getFirstName(){
return firstName;
}
public String getSurname(){
return surname;
}
public static class Builder {
private String firstName;
private String surname;
public Builder setFirstName(String firstName) {
this.firstName = firstName;
return this;
}
public Builder setSurname(String surname) {
this.surname = surname;
return this;
}
public User build(){
return new User(this);
}
}
public static void main(String[] args) {
User.Builder builder = new User.Builder();
User user = builder.setFirstName("John").setSurname("Doe").build();
}
}
Unless you have overlapping variable names, its really just for clarity when you're reading the code.
#William Brendel answer provided three different use cases in nice way.
Use case 1:
Offical java documentation page on this provides same use-cases.
Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.
It covers two examples :
Using this with a Field and Using this with a Constructor
Use case 2:
Other use case which has not been quoted in this post: this can be used to synchronize the current object in a multi-threaded application to guard critical section of data & methods.
synchronized(this){
// Do some thing.
}
Use case 3:
Implementation of Builder pattern depends on use of this to return the modified object.
Refer to this post
Keeping builder in separate class (fluent interface)
Google turned up a page on the Sun site that discusses this a bit.
You're right about the variable; this can indeed be used to differentiate a method variable from a class field.
private int x;
public void setX(int x) {
this.x=x;
}
However, I really hate that convention. Giving two different variables literally identical names is a recipe for bugs. I much prefer something along the lines of:
private int x;
public void setX(int newX) {
x=newX;
}
Same results, but with no chance of a bug where you accidentally refer to x when you really meant to be referring to x instead.
As to using it with a method, you're right about the effects; you'll get the same results with or without it. Can you use it? Sure. Should you use it? Up to you, but given that I personally think it's pointless verbosity that doesn't add any clarity (unless the code is crammed full of static import statements), I'm not inclined to use it myself.
Following are the ways to use ‘this’ keyword in java :
Using this keyword to refer current class instance variables
Using this() to invoke current class constructor
Using this keyword to return the current class instance
Using this keyword as method parameter
https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
when there are two variables one instance variable and other local variable of the same name then we use this. to refer current executing object to avoid the conflict between the names.
this is a reference to the current object. It is used in the constructor to distinguish between the local and the current class variable which have the same name. e.g.:
public class circle {
int x;
circle(int x){
this.x =x;
//class variable =local variable
}
}
this can also be use to call one constructor from another constructor. e.g.:
public class circle {
int x;
circle() {
this(1);
}
circle(int x) {
this.x = x;
}
}
Will be there any difference if I use "x" instead of "this.x" in some of the methods?
Usually not. But it makes a difference sometimes:
class A {
private int i;
public A(int i) {
this.i = i; // this.i can be used to disambiguate the i being referred to
}
}
If I just use "method()", will it not be, by default, applied to the current object?
Yes. But if needed, this.method() clarifies that the call is made by this object.
this does not affect resulting code - it is compilation time operator and the code generated with or without it will be the same. When you have to use it, depends on context. For example you have to use it, as you said, when you have local variable that shadows class variable and you want refer to class variable and not local one.
edit: by "resulting code will be the same" I mean of course, when some variable in local scope doesn't hide the one belonging to class. Thus
class POJO {
protected int i;
public void modify() {
i = 9;
}
public void thisModify() {
this.i = 9;
}
}
resulting code of both methods will be the same. The difference will be if some method declares local variable with the same name
public void m() {
int i;
i = 9; // i refers to variable in method's scope
this.i = 9; // i refers to class variable
}
With respect to William Brendel's posts and dbconfessions question, regarding case 2. Here is an example:
public class Window {
private Window parent;
public Window (Window parent) {
this.parent = parent;
}
public void addSubWindow() {
Window child = new Window(this);
list.add(child);
}
public void printInfo() {
if (parent == null) {
System.out.println("root");
} else {
System.out.println("child");
}
}
}
I've seen this used, when building parent-child relation's with objects. However, please note that it is simplified for the sake of brevity.
To make sure that the current object's members are used. Cases where thread safety is a concern, some applications may change the wrong objects member values, for that reason this should be applied to the member so that the correct object member value is used.
If your object is not concerned with thread safety then there is no reason to specify which object member's value is used.

Homework: Date comparison [duplicate]

I know that this refers to a current object. But I do not know when I really need to use it. For example, will be there any difference if I use x instead of this.x in some of the methods? May be x will refer to a variable which is local for the considered method? I mean variable which is seen only in this method.
What about this.method()? Can I use it? Should I use it. If I just use method(), will it not be, by default, applied to the current object?
The this keyword is primarily used in three situations. The first and most common is in setter methods to disambiguate variable references. The second is when there is a need to pass the current class instance as an argument to a method of another object. The third is as a way to call alternate constructors from within a constructor.
Case 1: Using this to disambiguate variable references. In Java setter methods, we commonly pass in an argument with the same name as the private member variable we are attempting to set. We then assign the argument x to this.x. This makes it clear that you are assigning the value of the parameter "name" to the instance variable "name".
public class Foo
{
private String name;
public void setName(String name) {
this.name = name;
}
}
Case 2: Using this as an argument passed to another object.
public class Foo
{
public String useBarMethod() {
Bar theBar = new Bar();
return theBar.barMethod(this);
}
public String getName() {
return "Foo";
}
}
public class Bar
{
public void barMethod(Foo obj) {
obj.getName();
}
}
Case 3: Using this to call alternate constructors. In the comments, trinithis correctly pointed out another common use of this. When you have multiple constructors for a single class, you can use this(arg0, arg1, ...) to call another constructor of your choosing, provided you do so in the first line of your constructor.
class Foo
{
public Foo() {
this("Some default value for bar");
//optional other lines
}
public Foo(String bar) {
// Do something with bar
}
}
I have also seen this used to emphasize the fact that an instance variable is being referenced (sans the need for disambiguation), but that is a rare case in my opinion.
The second important use of this (beside hiding with a local variable as many answers already say) is when accessing an outer instance from a nested non-static class:
public class Outer {
protected int a;
public class Inner {
protected int a;
public int foo(){
return Outer.this.a;
}
public Outer getOuter(){
return Outer.this;
}
}
}
You only need to use this - and most people only use it - when there's an overlapping local variable with the same name. (Setter methods, for example.)
Of course, another good reason to use this is that it causes intellisense to pop up in IDEs :)
The only need to use the this. qualifier is when another variable within the current scope shares the same name and you want to refer to the instance member (like William describes). Apart from that, there's no difference in behavior between x and this.x.
"this" is also useful when calling one constructor from another:
public class MyClass {
public MyClass(String foo) {
this(foo, null);
}
public MyClass(String foo, String bar) {
...
}
}
There are a lot of good answers, but there is another very minor reason to put this everywhere. If you have tried opening your source codes from a normal text editor (e.g. notepad etc), using this will make it a whole lot clearer to read.
Imagine this:
public class Hello {
private String foo;
// Some 10k lines of codes
private String getStringFromSomewhere() {
// ....
}
// More codes
public class World {
private String bar;
// Another 10k lines of codes
public void doSomething() {
// More codes
foo = "FOO";
// More codes
String s = getStringFromSomewhere();
// More codes
bar = s;
}
}
}
This is very clear to read with any modern IDE, but this will be a total nightmare to read with a regular text editor.
You will struggle to find out where foo resides, until you use the editor's "find" function. Then you will scream at getStringFromSomewhere() for the same reason. Lastly, after you have forgotten what s is, that bar = s is going to give you the final blow.
Compare it to this:
public void doSomething() {
// More codes
Hello.this.foo = "FOO";
// More codes
String s = Hello.this.getStringFromSomewhere();
// More codes
this.bar = s;
}
You know foo is a variable declared in outer class Hello.
You know getStringFromSomewhere() is a method declared in outer class as well.
You know that bar belongs to World class, and s is a local variable declared in that method.
Of course, whenever you design something, you create rules. So while designing your API or project, if your rules include "if someone opens all these source codes with a notepad, he or she should shoot him/herself in the head," then you are totally fine not to do this.
this is useful in the builder pattern.
public class User {
private String firstName;
private String surname;
public User(Builder builder){
firstName = builder.firstName;
surname = builder.surname;
}
public String getFirstName(){
return firstName;
}
public String getSurname(){
return surname;
}
public static class Builder {
private String firstName;
private String surname;
public Builder setFirstName(String firstName) {
this.firstName = firstName;
return this;
}
public Builder setSurname(String surname) {
this.surname = surname;
return this;
}
public User build(){
return new User(this);
}
}
public static void main(String[] args) {
User.Builder builder = new User.Builder();
User user = builder.setFirstName("John").setSurname("Doe").build();
}
}
Unless you have overlapping variable names, its really just for clarity when you're reading the code.
#William Brendel answer provided three different use cases in nice way.
Use case 1:
Offical java documentation page on this provides same use-cases.
Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.
It covers two examples :
Using this with a Field and Using this with a Constructor
Use case 2:
Other use case which has not been quoted in this post: this can be used to synchronize the current object in a multi-threaded application to guard critical section of data & methods.
synchronized(this){
// Do some thing.
}
Use case 3:
Implementation of Builder pattern depends on use of this to return the modified object.
Refer to this post
Keeping builder in separate class (fluent interface)
Google turned up a page on the Sun site that discusses this a bit.
You're right about the variable; this can indeed be used to differentiate a method variable from a class field.
private int x;
public void setX(int x) {
this.x=x;
}
However, I really hate that convention. Giving two different variables literally identical names is a recipe for bugs. I much prefer something along the lines of:
private int x;
public void setX(int newX) {
x=newX;
}
Same results, but with no chance of a bug where you accidentally refer to x when you really meant to be referring to x instead.
As to using it with a method, you're right about the effects; you'll get the same results with or without it. Can you use it? Sure. Should you use it? Up to you, but given that I personally think it's pointless verbosity that doesn't add any clarity (unless the code is crammed full of static import statements), I'm not inclined to use it myself.
Following are the ways to use ‘this’ keyword in java :
Using this keyword to refer current class instance variables
Using this() to invoke current class constructor
Using this keyword to return the current class instance
Using this keyword as method parameter
https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
when there are two variables one instance variable and other local variable of the same name then we use this. to refer current executing object to avoid the conflict between the names.
this is a reference to the current object. It is used in the constructor to distinguish between the local and the current class variable which have the same name. e.g.:
public class circle {
int x;
circle(int x){
this.x =x;
//class variable =local variable
}
}
this can also be use to call one constructor from another constructor. e.g.:
public class circle {
int x;
circle() {
this(1);
}
circle(int x) {
this.x = x;
}
}
Will be there any difference if I use "x" instead of "this.x" in some of the methods?
Usually not. But it makes a difference sometimes:
class A {
private int i;
public A(int i) {
this.i = i; // this.i can be used to disambiguate the i being referred to
}
}
If I just use "method()", will it not be, by default, applied to the current object?
Yes. But if needed, this.method() clarifies that the call is made by this object.
this does not affect resulting code - it is compilation time operator and the code generated with or without it will be the same. When you have to use it, depends on context. For example you have to use it, as you said, when you have local variable that shadows class variable and you want refer to class variable and not local one.
edit: by "resulting code will be the same" I mean of course, when some variable in local scope doesn't hide the one belonging to class. Thus
class POJO {
protected int i;
public void modify() {
i = 9;
}
public void thisModify() {
this.i = 9;
}
}
resulting code of both methods will be the same. The difference will be if some method declares local variable with the same name
public void m() {
int i;
i = 9; // i refers to variable in method's scope
this.i = 9; // i refers to class variable
}
With respect to William Brendel's posts and dbconfessions question, regarding case 2. Here is an example:
public class Window {
private Window parent;
public Window (Window parent) {
this.parent = parent;
}
public void addSubWindow() {
Window child = new Window(this);
list.add(child);
}
public void printInfo() {
if (parent == null) {
System.out.println("root");
} else {
System.out.println("child");
}
}
}
I've seen this used, when building parent-child relation's with objects. However, please note that it is simplified for the sake of brevity.
To make sure that the current object's members are used. Cases where thread safety is a concern, some applications may change the wrong objects member values, for that reason this should be applied to the member so that the correct object member value is used.
If your object is not concerned with thread safety then there is no reason to specify which object member's value is used.

Passing object by reference to a thread

Let's say I have a class called Object and a thread called ObjectCreator that manages the creation of an Object. For the sake of simplicity, Object has attributes: objectNumber and objectName.
If I were to create an instance of Object called instance, it would be held by ObjectCreator. Now let's say I needed another thread (let's call it ObjectChanger) to be able to see and manipulate instance; does it make sense to turn instance into a static Object?
I've managed to see results by making instance static so now I can do something like:
ObjectCreator.instance.getName();
Where getName() is a method of Object. From what I've read from answers to similar questions, static things are evil and there's always workarounds. One suggestion I've read is to pass instance to ObjectChanger as an argument for its constructor but what if instance wasn't created yet at the time I need to create an ObjectChanger?
Perhaps this question is more about OOP concepts than multi-threading or it may be a duplicate so forgive me but I'm quite lost here.
EDIT: To address frankie's and Jim's suggestions, here are some code snippets:
Object:
class Object
{
private String objectName = "Something";
private int objectNumber = 1;
public synchronized void changeNumber(int newNumber)
{
objectNumber = newNumber;
}
}
ObjectCreator:
class ObjectCreator extends Thread
{
static Object instance;
public ObjectCreator (Object something)
{
instance = something;
}
static void createObject()
{
...
}
static Object getObject()
{
return instance;
}
}
ObjectChanger:
public class ObjectChanger extends Thread
{
private Object currentInstance = null;
private int instanceNumber = null;
public void run()
{
currentInstance = ObjectCreator.getObject(); //If I were to make getObject() non-static, this line churns up an error
instanceNumber = currentInstance.getObjectNumber();
currentInstance.changeNumber(2); //valid?
}
}
If you want a thread to obtain access to an object not created within it, you must ensure that said thread has a path of references which it can follow, leading to the new object.
Consider the following code, with no threads involved.
class MyObject { /* ... */ }
interface MyObjectProvider {
MyObject getMyObject();
}
class Creator implements MyObjectProvider {
private MyObject obj;
/* ... */
#Override
public MyObject getMyObject() {
return obj;
}
/** Invoked at some point in time. */
void createMyObject() {
obj = new MyObject();
}
}
class Consumer {
private MyObjectProvider provider;
Consumer(MyObjectProvider mop) {
provider = mop;
}
void consume() {
// At some point in time...
MyObject o = provider.getMyObject();
}
}
Example of a program:
public static void main(String[] args) {
Creator creator = new Creator();
Consumer consumer = new Consumer(creator);
creator.createMyObject();
consumer.consume();
}
When you add threads to the mix, some code has to change, but the struture is the same.
The idea is to run the Creator in a thread, and the Consumer in another, as you've pointed out.
So, in short, these are the things you should be looking into:
Concurrency control: look into data races, synchronized, mutual exclusion, and their friends. Start here.
wait and notify, if the Consumer should wait for MyObject to be created. Look here.
When you have a nice grasp on these concepts, you may look into the volatile keyword (watch out for its pitfalls), and the java.util.concurrent package which provides better concurrency primitives, concurrent collections, and atomic variables.
You can put your objects in a list structure like Vector and store them in the ObjectCreator. Add a getter method to ObjectCreator which will accept an index of the object to be received.
This is just a skeleton showing the basic structure. Error handling is left as an exercise :-)
public class MyObject { ... }
...
public class MyObjectCreator {
private Map<String,MyObject> createdObjects = new HashMap<>();
public MyObject makeNewObject(int objNum, String objName)
{
MyObject o = new MyObject(objNum, objName);
this.createdObjects.put(objName,o);
}
public MyObject getObject(String objName)
{
return this.createdObjects.get(objName);
}
}
...
public class MyProgram {
public static void main(String[] args)
{
MyObjectCreator oc = new MyObjectCreator();
MyObject mo = oc.makeNewObject(10,"aNewObject");
...
MyObject o = oc.get("aNewObject");
...
If you only want to change the values of the fields of your class, you should just pass the object into your newly created thread. Then there is really no need to keep a static reference around in a holder class.
But as commented already, we need a bit more information to get to what you want to do with your object and thread.
Why cant you just make an getter in the ObjectCreator class that retrieves said Object?
ex: ObjectCreater.getMyObject()
EDIT:
I think you're looking for something like this if Im not mistaken:
public class ObjectCreator{
ArrayList<Object> children;
public ObjectCreator(){
children = new ArrayList<Object>();
}
//returns back index in children array (for accessing from other threads)
public int createObject( whatever params here ){
Object o = new Object( params );
children.add(o);
return children.size()-1;
}
}
since I dont know much about the problem you're trying to solve, Im not sure if it has to be thread safe, if you want these objects mapped, or accessed differently, but Im confused where all the confusion about static is coming...

Java publish safely with final

just to make sure.
I am following the Java Concurrency in practice book.
When it comes to publish safely especially with final, it is clear to me that firstly the reference will be visible to all other threads and secondly the state of the published object is visible to any other thread but the question here is if the state of the referenced array elements is guaranteed to be visible with the state it was published? (surely as long no one modifies those data objects).
Example:
#Mutable
public class NotThreadsafeDataObject {
private String message;
public NotThreadsafeDataObject (String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
Now let's publish safely an array of mutable objects:
public class Publish {
public final NotThreadsafeDataObject[] publish;
public Publish() {
publish = new NotThreadsafeDataObject[] { new NotThreadsafeDataObject("one"), new NotThreadsafeDataObject("two")};
}
}
If we speak in terms presented in "Java Concurrency in Practice" then your array is an "effectively immutable" object. For such objects safe publication is always necessary for not corrupting the internal state. So your code is OK, because you are using safe publication. More specifically the "final" keyword memory semantics guarantees that a thread accessing the final field will see everything that happened before the field was written ("happen-before" is established).
I am pretty sure that you can still modify the values of your individual mutable objects in your Array. I.e.
publish[0].setMessaage("Hello");
would work just fine. And also I believe you can remove objects from your array. It's the Array reference that can not be changed because it is declared final. If you want to have completely immutable collection I would work with List that is declared as final and then create a new separate List, populate it and then use method public static List unmodifiableList(List list) to assig it to your final list:
ublic class Publish {
public static final List<NotThreadsafeDataObject> publish;
static {
init();
}
private static void synchronized init() {
List<NotThreadsafeDataObject> list = new ArrayList<>();
list.add(new NotThreadsafeDataObject("one");
list.add(new NotThreadsafeDataObject("two");
publish = Collections.unmodifiableList(list);
}
}
This makes bulletproof completely immutable list that neither reference to it nor its contents could be changed.

Categories

Resources