dev.responsive.kafka.internal.db.TableCache Maven / Gradle / Ivy
The newest version!
/*
* Copyright 2024 Responsive Computing, Inc.
*
* This source code is licensed under the Responsive Business Source License Agreement v1.0
* available at:
*
* https://www.responsive.dev/legal/responsive-bsl-10
*
* This software requires a valid Commercial License Key for production use. Trial and commercial
* licenses can be obtained at https://www.responsive.dev
*/
package dev.responsive.kafka.internal.db;
import dev.responsive.kafka.internal.db.spec.RemoteTableSpec;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;
import javax.annotation.concurrent.ThreadSafe;
/**
* A {@code ThreadSafeTableFactory} creates and maintains a collection
* of {@link RemoteTable}s, ensuring that the statements to create the
* table are only prepared once during the lifetime of the application.
*/
@ThreadSafe
public class TableCache> {
@FunctionalInterface
public interface Factory {
T create(final RemoteTableSpec spec)
throws InterruptedException, TimeoutException;
}
private final Map tables = new HashMap<>();
private final Factory factory;
public TableCache(final Factory factory) {
this.factory = factory;
}
/**
* Creates a table with the supplied {@code tableName} with the
* desired schema.
*/
public synchronized T create(RemoteTableSpec spec)
throws InterruptedException, TimeoutException {
final T existing = tables.get(spec.tableName());
if (existing != null) {
return existing;
}
final T table = factory.create(spec);
tables.put(spec.tableName(), table);
return table;
}
/**
* @param name the name of the table
* @return the table, if it was already created by {@link #create(RemoteTableSpec)}
*/
public synchronized T getTable(final String name) {
return tables.get(name);
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy