-1

I want to ask you for help with advanced synchronization. I have class like this:

public class Manager{
    private ClassMatcher classMatcher;

    public ClassMatcher getClassMatcher(){
        return this.classMatcher;
    }
    public void setClassMatcher(ClassMatcher classMatcher){
        this.classMatcher = classMatcher;
    }
}

Object Manager can be called from more Threads, so methods: getClassMatcher and setClassMatcher should be synchronized. But in that case method getClassMatcher can be accessed only by one Thread in the same time.

Is there some way how to solve it ?
Well perhaps I can use Locks or AtomicReferences.

Thank you for any advice, it will be really helpful

farget93
  • 29
  • 2
  • Why do you think the setter needs to be synchronized, and why do you think doing so would affect the getter? – shmosel Aug 18 '17 at 19:32
  • How is this advanced synchronization? Also, solve what? Making the methods synchronized is one way of handling multiple threads accessing the `Manager` class. – Kayaman Aug 18 '17 at 19:33
  • Without clearly describing how this is used, it is not really possible to suggest a correct approach. You might also want to read https://stackoverflow.com/questions/11459543/java-synchronized-getters-and-setters?rq=1 – Mark Rotteveel Aug 18 '17 at 21:20

2 Answers2

-1

You don't need to synchronize those methods, but class ClassMatcher should be thread-safe.

Call get or set won't cause problems in your case because set method only replaces the reference of class member to a new object.

Giovani Grifante
  • 452
  • 3
  • 14
-1

I can't see any reason why you need synchronization in such example because your accessors don't do much work with shared state which really can cause some concurrent issues.

For instance, here we have race condition and synchronization needed:

   public int get() {
      if (a == b) {
        return a;
      } else {
        return b;
      }
    }

PS: as @shmosel mentioned you may mark your variable as volatile to be sure that you get() the most actual version of your classMatcher

vk23
  • 468
  • 7
  • 16
  • Synchronization (or other measures) may be necessary for correct publication and visibility of changes through the setter to other threads. – Mark Rotteveel Aug 18 '17 at 21:18
  • Or through synchronization, or through atomic updaters, or... Erich is my point; your answer is not correct and incomplete at best. – Mark Rotteveel Aug 19 '17 at 06:02