Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
200 views
in Technique[技术] by (71.8m points)

java - Is this a safe publication of object?

I have a class Item

class Item {
  public int count;
  public Item(int count) {
    this.count = count;
  }
}

Then, I will put a reference to Item in a field of other class

class Holder {
  public Item item;
  public Holder() {
    item = new Item(50);
  }
}

Can this new Item object be safely published? If not, why? According to Java Concurrency in Practice, the new Item is published without being fully constructed, but in my opinion the new Item is fully constructed: its this reference doesn't escape and the reference to it and its state is published at the same time, so the consumer thread will not see a stale value. Or is it the visibility problem. I don't exactly know the reason.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Can this new Item object be safely published? If not, why?

The issue revolves around optimizations and reordering of instructions. When you have two threads that are using a constructed object without synchronization, it may happen that the compiler decides to reorder instructions for efficiency sake and allocate the memory space for an object and store its reference in the item field before it finishes with the constructor and the field initialization. Or it can reorder the memory synchronization so that other threads perceive it that way.

If you mark the item field as final then the constructor is guaranteed to finish initialization of that field as part of the constructor. Otherwise you will have to synchronize on a lock before using it. This is part of the Java language definition.

Here's another couple references:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...