/*
 * Copyright 2012-2015 JetBrains s.r.o
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package jetbrains.jetpad.base;

public final class ThreadSafeAsync<ItemT> implements Async<ItemT> {
  private final SimpleAsync<ItemT> myAsync;

  public ThreadSafeAsync() {
    myAsync = new SimpleAsync<>();
  }

  @Override
  public Registration onSuccess(Handler<? super ItemT> successHandler) {
    synchronized (myAsync) {
      return myAsync.onSuccess(successHandler);
    }
  }

  @Override
  public Registration onResult(Handler<? super ItemT> successHandler, Handler<Throwable> failureHandler) {
    synchronized (myAsync) {
      return myAsync.onResult(successHandler, failureHandler);
    }
  }

  @Override
  public Registration onFailure(Handler<Throwable> failureHandler) {
    synchronized (myAsync) {
      return myAsync.onFailure(failureHandler);
    }
  }

  public void success(ItemT item) {
    synchronized (myAsync) {
      myAsync.success(item);
    }
  }

  public void failure(Throwable throwable) {
    synchronized (myAsync) {
      myAsync.failure(throwable);
    }
  }
}
@@ -928,32 +928,40 @@
  %7B%0A      return 
+safeReg(
 myAsync.onSucces
@@ -969,32 +969,33 @@
 (successHandler)
+)
 ;%0A    %7D%0A  %7D%0A%0A  @
@@ -1144,32 +1144,40 @@
  %7B%0A      return 
+safeReg(
 myAsync.onResult
@@ -1200,32 +1200,33 @@
  failureHandler)
+)
 ;%0A    %7D%0A  %7D%0A%0A  @
@@ -1345,16 +1345,24 @@
  return 
+safeReg(
 myAsync.
@@ -1386,16 +1386,18 @@
 Handler)
+) 
 ;%0A    %7D%0A
@@ -1393,32 +1393,254 @@
 )) ;%0A    %7D%0A  %7D%0A%0A
+  private Registration safeReg(final Registration r) %7B%0A    return new Registration() %7B%0A      @Override%0A      protected void doRemove() %7B%0A        synchronized (myAsync) %7B%0A          r.remove();%0A        %7D%0A      %7D%0A    %7D;%0A  %7D%0A%0A
   public void su

fix ThreadSafeAsync registrations