All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.google.cloud.pubsublite.beam.PublisherCache Maven / Gradle / Ivy

There is a newer version: 0.23.0
Show newest version
/*
 * Copyright 2020 Google LLC
 *
 * 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 com.google.cloud.pubsublite.beam;

import static com.google.cloud.pubsublite.internal.UncheckedApiPreconditions.checkArgument;

import com.google.api.core.ApiService.Listener;
import com.google.api.core.ApiService.State;
import com.google.api.gax.rpc.ApiException;
import com.google.cloud.pubsublite.MessageMetadata;
import com.google.cloud.pubsublite.internal.Publisher;
import com.google.cloud.pubsublite.internal.wire.SystemExecutors;
import com.google.common.annotations.VisibleForTesting;
import com.google.errorprone.annotations.concurrent.GuardedBy;
import java.util.HashMap;

/** A map of working publishers by PublisherOptions. */
class PublisherCache implements AutoCloseable {
  @GuardedBy("this")
  private final HashMap> livePublishers =
      new HashMap<>();

  private synchronized void evict(PublisherOptions options) {
    livePublishers.remove(options);
  }

  synchronized Publisher get(PublisherOptions options) throws ApiException {
    checkArgument(options.usesCache());
    Publisher publisher = livePublishers.get(options);
    if (publisher != null) {
      return publisher;
    }
    publisher = Publishers.newPublisher(options);
    livePublishers.put(options, publisher);
    publisher.addListener(
        new Listener() {
          @Override
          public void failed(State s, Throwable t) {
            evict(options);
          }
        },
        SystemExecutors.getFuturesExecutor());
    publisher.startAsync().awaitRunning();
    return publisher;
  }

  @VisibleForTesting
  synchronized void set(PublisherOptions options, Publisher toCache) {
    livePublishers.put(options, toCache);
  }

  @Override
  public synchronized void close() {
    livePublishers.forEach(((options, publisher) -> publisher.stopAsync()));
    livePublishers.clear();
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy