Blocking Strategy Using PropertyChangeListener

I defined a class with a number of “observable” properties. Internally, the class contains one thread that performs I / O; eg.

public class Foo {
  private final PropertyChangeSupport support;
  private State state;

  public Foo() { this.support = new PropertyChangeSupport(this); }

  public synchronized State getState() { return state; }

  public synchronized void setState(State state) {
    if (this.state != state) {
      State oldState = this.state;
      this.state = state;

      // Fire property change *whilst still holding the lock*.
      support.firePropertyChange("state", oldState, state);
    }
  }

  public synchronized void start() {
    // Start I/O Thread, which will call setState(State) in some circumstances.
    new Thread(new Runnable() ...
  }
}

My question is: should I avoid triggering property change events while holding the class lock? ... or maybe I should fire property change events from a single allocated stream (for example, the event-multicaster stream)?

, A : Bar, Foo . , - setState(State) Foo, Bar ... . , , , .

volatile synchronized, kludge; -, , , , .

+3
1

, , , , ( , ):

public void setState(State state) {
    State oldState = null;
    synchronized (this) {
      if (this.state != state) {
        oldState = this.state;
        this.state = state;
      }
    }

    if (oldState != null)
      support.firePropertyChange("state", oldState, state);
  }

. ( java.util.concurrent).


, .

: . , -, -. , .

, , - - , . ; .

: . , . : , , . : () .

, ( ), , , , . , , . , , .

: . java.util.concurrent.

+3

Source: https://habr.com/ru/post/1718452/


All Articles