This commit is contained in:
Rob Austin
2014-11-04 14:29:06 +00:00
parent cff7c5bea8
commit a0c89935f5
76 changed files with 1248 additions and 2153 deletions
@@ -18,7 +18,7 @@
package net.openhft.chronicle.map;
import net.openhft.chronicle.hash.ThrottlingConfig;
import net.openhft.chronicle.hash.replication.ThrottlingConfig;
import net.openhft.lang.io.ByteBufferBytes;
import net.openhft.lang.io.Bytes;
import net.openhft.lang.thread.NamedThreadFactory;
@@ -19,6 +19,7 @@
package net.openhft.chronicle.map;
import net.openhft.chronicle.hash.*;
import net.openhft.chronicle.hash.replication.*;
import net.openhft.chronicle.hash.serialization.MetaBytesInterop;
import net.openhft.chronicle.hash.serialization.MetaBytesWriter;
import net.openhft.chronicle.hash.serialization.MetaProvider;
@@ -40,8 +41,11 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@@ -103,8 +107,6 @@ public abstract class AbstractChronicleMapBuilder<K, V,
SerializationBuilder<K> keyBuilder;
SerializationBuilder<V> valueBuilder;
private Map<Class<? extends Replicator>, Replicator> replicators = new HashMap<Class<? extends Replicator>, Replicator>();
// used when configuring the number of segments.
private int minSegments = -1;
private int actualSegments = -1;
@@ -133,10 +135,8 @@ public abstract class AbstractChronicleMapBuilder<K, V,
private V defaultValue = null;
private DefaultValueProvider<K, V> defaultValueProvider = NullValueProvider.INSTANCE;
private PrepareValueBytes<K, V> prepareValueBytes = null;
private byte identifier = -1;
private StatelessBuilder statelessBuilder;
private File file;
private SimpleReplication simpleReplication = null;
AbstractChronicleMapBuilder(Class<K> keyClass, Class<V> valueClass) {
keyBuilder = new SerializationBuilder<K>(keyClass, SerializationBuilder.Role.KEY);
@@ -283,14 +283,14 @@ public abstract class AbstractChronicleMapBuilder<K, V,
return self();
}
int entrySize() {
int entrySize(boolean replicated) {
if (entrySize > 0)
return entryAndValueAlignment().alignSize(entrySize);
int size = metaDataBytes;
int keySize = keySize();
size += keyBuilder.sizeMarshaller().sizeEncodingSize(keySize);
size += keySize;
if (useReplication())
if (replicated)
size += ReplicatedChronicleMap.ADDITIONAL_ENTRY_BYTES;
int valueSize = valueSize();
size += valueBuilder.sizeMarshaller().sizeEncodingSize(valueSize);
@@ -559,43 +559,6 @@ public abstract class AbstractChronicleMapBuilder<K, V,
return toString().hashCode();
}
public B replicators(byte identifier, ReplicationConfig... replicationConfigs) {
this.identifier = identifier;
this.replicators.clear();
for (ReplicationConfig replicationConfig : replicationConfigs) {
Replicator replicator;
if (replicationConfig instanceof TcpReplicationConfig) {
replicator = Replicators.tcp((TcpReplicationConfig) replicationConfig);
} else if (replicationConfig instanceof UdpReplicationConfig) {
replicator = Replicators.udp((UdpReplicationConfig) replicationConfig);
} else
throw new UnsupportedOperationException();
this.replicators.put(replicator.getClass(), replicator);
}
return self();
}
public B channel(ChannelProvider.ChronicleChannel chronicleChannel) {
this.identifier = chronicleChannel.identifier();
this.replicators.clear();
replicators.put(chronicleChannel.getClass(), chronicleChannel);
return self();
}
@Override
public B disableReplication() {
identifier = -1;
replicators.clear();
return self();
}
@Override
public B timeProvider(TimeProvider timeProvider) {
this.timeProvider = timeProvider;
@@ -656,15 +619,9 @@ public abstract class AbstractChronicleMapBuilder<K, V,
}
@Override
public B stateless(@NotNull StatelessBuilder statelessBuilder) {
this.statelessBuilder = statelessBuilder;
return self();
}
@Override
public B file(File file) throws IOException {
this.file = file;
return self();
public StatelessClientConfig<ChronicleMap<K, V>> statelessClient(
InetSocketAddress remoteAddress) {
return new StatelessMapConfig<>(this.clone(), remoteAddress);
}
/**
@@ -748,7 +705,7 @@ public abstract class AbstractChronicleMapBuilder<K, V,
/**
* Non-public because should be called only after {@link #preMapConstruction()}
* Non-public because should be called only after {@link #preMapConstruction(boolean)}
*/
DefaultValueProvider<K, V> defaultValueProvider() {
if (defaultValueProvider != null)
@@ -766,7 +723,43 @@ public abstract class AbstractChronicleMapBuilder<K, V,
return new ConstantValueProvider<K, V>(defaultValue, metaValueWriter, valueWriter);
}
public ChronicleMap<K, V> createWithFile(File file) throws IOException {
@Override
public B replication(SimpleReplication replication) {
this.simpleReplication = replication;
return self();
}
@Override
public B replication(byte identifier, TcpConfig tcpTransportAndNetwork) {
return replication(SimpleReplication.builder()
.tcpTransportAndNetwork(tcpTransportAndNetwork).create(identifier));
}
@Override
public ChronicleHashInstanceConfig<ChronicleMap<K, V>> instance() {
return new InstanceConfig<>(this.clone(), simpleReplication, null, null);
}
@Override
public ChronicleMap<K, V> createPersistedTo(File file) throws IOException {
return createWithFile(file, simpleReplication, null);
}
@Override
public ChronicleMap<K, V> create() throws IOException {
return createWithoutFile(simpleReplication, null);
}
ChronicleMap<K, V> create(InstanceConfig<K, V> ib) throws IOException {
if (ib.file != null) {
return createWithFile(ib.file, ib.simpleReplication, ib.channel);
} else {
return createWithoutFile(ib.simpleReplication, ib.channel);
}
}
ChronicleMap<K, V> createWithFile(File file, SimpleReplication simpleReplication,
ReplicationChannel channel) throws IOException {
for (int i = 0; i < 10; i++) {
if (file.exists() && file.length() > 0) {
FileInputStream fis = new FileInputStream(file);
@@ -776,7 +769,7 @@ public abstract class AbstractChronicleMapBuilder<K, V,
(VanillaChronicleMap<K, ?, ?, V, ?, ?>) ois.readObject();
map.headerSize = roundUpMapHeaderSize(fis.getChannel().position());
map.createMappedStoreAndSegments(file);
return establishReplication(map);
return establishReplication(map, simpleReplication, channel);
} catch (ClassNotFoundException e) {
throw new IOException(e);
} finally {
@@ -796,7 +789,7 @@ public abstract class AbstractChronicleMapBuilder<K, V,
if (!file.exists())
throw new FileNotFoundException("Unable to create " + file);
VanillaChronicleMap<K, ?, ?, V, ?, ?> map = newMap();
VanillaChronicleMap<K, ?, ?, V, ?, ?> map = newMap(simpleReplication, channel);
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
@@ -809,54 +802,66 @@ public abstract class AbstractChronicleMapBuilder<K, V,
oos.close();
}
return establishReplication(map);
return establishReplication(map, simpleReplication, channel);
}
@Override
public ChronicleMap<K, V> create() throws IOException {
if (statelessBuilder != null)
return createStatelessMap(statelessBuilder);
return (file != null) ? createWithFile(file) : createWithoutFile();
}
private ChronicleMap<K, V> createWithoutFile() throws IOException {
VanillaChronicleMap<K, ?, ?, V, ?, ?> map = newMap();
/**
* Only for testing.
*
* @param identifier id
* @return map
*/
ChronicleMap<K, V> createReplicated(byte identifier) throws IOException {
VanillaChronicleMap<K, ?, ?, V, ?, ?> map =
new ReplicatedChronicleMap<K, Object, MetaBytesInterop<K, Object>,
V, Object, MetaBytesWriter<V, Object>>(this, identifier);
BytesStore bytesStore = new DirectStore(JDKObjectSerializer.INSTANCE,
map.sizeInBytes(), true);
map.createMappedStoreAndSegments(bytesStore);
return establishReplication(map);
return map;
}
private ChronicleMap<K, V> createStatelessMap(StatelessBuilder statelessBuilder) throws IOException {
preMapConstruction();
private ChronicleMap<K, V> createWithoutFile(
SimpleReplication simpleReplication, ReplicationChannel channel) throws IOException {
VanillaChronicleMap<K, ?, ?, V, ?, ?> map = newMap(simpleReplication, channel);
BytesStore bytesStore = new DirectStore(JDKObjectSerializer.INSTANCE,
map.sizeInBytes(), true);
map.createMappedStoreAndSegments(bytesStore);
return establishReplication(map, simpleReplication, channel);
}
ChronicleMap<K, V> createStatelessMap(StatelessMapConfig<K, V> statelessBuilder)
throws IOException {
preMapConstruction(false);
return new StatelessChronicleMap<K, V>(
statelessBuilder,
this);
}
private VanillaChronicleMap<K, ?, ?, V, ?, ?> newMap() throws IOException {
preMapConstruction();
if (useReplication()) {
private VanillaChronicleMap<K, ?, ?, V, ?, ?> newMap(
SimpleReplication simpleReplication, ReplicationChannel channel) throws IOException {
boolean replicated = simpleReplication != null || channel != null;
preMapConstruction(replicated);
if (replicated) {
byte identifier;
if (simpleReplication != null) {
identifier = simpleReplication.identifier();
} else {
identifier = channel.hub().identifier();
}
return new ReplicatedChronicleMap<K, Object, MetaBytesInterop<K, Object>,
V, Object, MetaBytesWriter<V, Object>>(this);
V, Object, MetaBytesWriter<V, Object>>(this, identifier);
} else {
return new VanillaChronicleMap<K, Object, MetaBytesInterop<K, Object>,
V, Object, MetaBytesWriter<V, Object>>(this);
}
}
private boolean useReplication() {
return identifier != -1;
}
void preMapConstruction() {
void preMapConstruction(boolean replicated) {
keyBuilder.objectSerializer(objectSerializer());
valueBuilder.objectSerializer(objectSerializer());
long maxSize = (long) entrySize() * figureBufferAllocationFactor();
long maxSize = (long) entrySize(replicated) * figureBufferAllocationFactor();
keyBuilder.maxSize(maxSize);
valueBuilder.maxSize(maxSize);
@@ -866,32 +871,37 @@ public abstract class AbstractChronicleMapBuilder<K, V,
valueBuilder.constantSizeBySample(sampleValue);
}
private ChronicleMap<K, V> establishReplication(VanillaChronicleMap<K, ?, ?, V, ?, ?> map)
throws IOException {
private ChronicleMap<K, V> establishReplication(
VanillaChronicleMap<K, ?, ?, V, ?, ?> map, SimpleReplication simpleReplication,
ReplicationChannel channel) throws IOException {
if (map instanceof ReplicatedChronicleMap) {
if (simpleReplication != null && channel != null) {
throw new AssertionError("Only one non-null replication should be passed");
}
ReplicatedChronicleMap result = (ReplicatedChronicleMap) map;
for (Replicator replicator : replicators.values()) {
if (replicator instanceof ChannelProvider.ChronicleChannel) {
ChannelProvider.ChronicleChannel channel =
(ChannelProvider.ChronicleChannel) replicator;
if (entrySize() > channel.provider().maxEntrySize()) {
throw new IllegalArgumentException("During ChannelProviderBuilder setup, " +
"maxEntrySize=" + channel.provider().maxEntrySize() +
" was specified, but map with " +
"entrySize=" + entrySize() + " is attempted to apply" +
"to the replicator");
}
List<Replicator> replicators = new ArrayList<>(2);
if (simpleReplication != null) {
if (simpleReplication.tcpTransportAndNetwork() != null)
replicators.add(Replicators.tcp(simpleReplication.tcpTransportAndNetwork()));
if (simpleReplication.udpTransport() != null)
replicators.add(Replicators.udp(simpleReplication.udpTransport()));
} else {
ReplicationHub hub = channel.hub();
int entrySize = entrySize(true);
if (entrySize > hub.maxEntrySize()) {
throw new IllegalArgumentException("During ChannelProviderBuilder setup, " +
"maxEntrySize=" + hub.maxEntrySize() +
" was specified, but map with " +
"entrySize=" + entrySize + " is attempted to apply to the replicator");
}
ChannelProvider provider = ChannelProvider.getProvider(hub);
ChannelProvider.ChronicleChannel ch = provider.createChannel(channel.channelId());
replicators.add(ch);
}
for (Replicator replicator : replicators) {
Closeable token = replicator.applyTo(this, result, result, map);
if (replicators.size() == 1 && token.getClass() == UdpReplicator.class) {
LOG.warn(
"MISSING TCP REPLICATION : The UdpReplicator only attempts to read data " +
"(it does not enforce or guarantee delivery), you should use" +
"the UdpReplicator if you have a large number of nodes, and you wish" +
"to receive the data before it becomes available on TCP/IP. Since data" +
"delivery is not guaranteed, it is recommended that you only use" +
"the UDP Replicator in conjunction with a TCP Replicator"
);
LOG.warn(Replicators.ONLY_UDP_WARN_MESSAGE);
}
result.addCloseable(token);
}
@@ -906,11 +916,7 @@ public abstract class AbstractChronicleMapBuilder<K, V,
VanillaChronicleMap.MAX_ENTRY_OVERSIZE_FACTOR);
}
public byte identifier() {
return identifier;
}
public int segmentHeaderSize() {
int segmentHeaderSize() {
int segments = actualSegments();
// reduce false sharing unless we have a lot of segments.
return segments <= 8192 ? 64 : 16;
@@ -17,7 +17,8 @@
package net.openhft.chronicle.map;
import net.openhft.chronicle.hash.ChronicleHashBuilder;
import net.openhft.chronicle.hash.serialization.AgileBytesMarshaller;
import net.openhft.chronicle.hash.serialization.BytesReader;
import net.openhft.chronicle.hash.serialization.BytesWriter;
import net.openhft.lang.io.Bytes;
import net.openhft.lang.io.serialization.BytesMarshallable;
import net.openhft.lang.io.serialization.BytesMarshaller;
@@ -223,9 +224,10 @@ public final class ChronicleMapBuilder<K, V>
return this;
}
public ChronicleMapBuilder<K, V> valueMarshaller(
@NotNull AgileBytesMarshaller<V> valueMarshaller) {
valueBuilder.agileMarshaller(valueMarshaller, null);
public ChronicleMapBuilder<K, V> valueMarshallers(
BytesWriter<V> valueWriter, BytesReader<V> valueReader) {
valueBuilder.writer(valueWriter);
valueBuilder.reader(valueReader, valueBuilder.factory());
return this;
}
}
@@ -1,38 +0,0 @@
/*
* Copyright 2014 Higher Frequency Trading
*
* http://www.higherfrequencytrading.com
*
* 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 net.openhft.chronicle.map;
import java.net.SocketAddress;
/**
* @author Rob Austin.
*/
public interface IdentifierListener {
/**
* checks the identifier that is unique and we haven't seen it before, unless it comes from the same port
* and host.
*
* @param remoteIdentifier remoteIdentifier
* @param remoteAddress remoteAddress
* @return true if unique
*/
boolean isIdentifierUnique(byte remoteIdentifier, SocketAddress remoteAddress);
}
@@ -18,8 +18,9 @@
package net.openhft.chronicle.map;
import net.openhft.chronicle.hash.TcpReplicationConfig;
import net.openhft.chronicle.hash.UdpReplicationConfig;
import net.openhft.chronicle.hash.replication.IdentifierListener;
import net.openhft.chronicle.hash.replication.TcpConfig;
import net.openhft.chronicle.hash.replication.UdpConfig;
import net.openhft.lang.collection.ATSDirectBitSet;
import net.openhft.lang.collection.DirectBitSet;
import net.openhft.lang.io.ByteBufferBytes;
@@ -41,7 +42,7 @@ import java.util.concurrent.atomic.AtomicReference;
import static java.nio.ByteBuffer.allocateDirect;
import static java.util.concurrent.TimeUnit.SECONDS;
import static net.openhft.chronicle.hash.UdpReplicationConfig.simple;
import static net.openhft.chronicle.hash.replication.UdpConfig.simple;
import static net.openhft.chronicle.map.ConcurrentExpiryMap.getDefaultAddress;
import static net.openhft.chronicle.map.DiscoveryNodeBytesMarshallable.ProposedNodes;
import static net.openhft.chronicle.map.NodeDiscoveryBroadcaster.BOOTSTRAP_BYTES;
@@ -55,7 +56,7 @@ import static net.openhft.chronicle.map.NodeDiscoveryBroadcaster.LOG;
public class NodeDiscovery {
private final AddressAndPort ourAddressAndPort;
private final UdpReplicationConfig udpConfig;
private final UdpConfig udpConfig;
private final DiscoveryNodeBytesMarshallable discoveryNodeBytesMarshallable;
private final AtomicReference<NodeDiscoveryEventListener> nodeDiscoveryEventListenerAtomicReference =
new AtomicReference<NodeDiscoveryEventListener>();
@@ -220,9 +221,11 @@ public class NodeDiscovery {
// add our identifier and host:port to the list of known identifiers
knownNodes.add(ourAddressAndPort, identifier);
final TcpReplicationConfig tcpConfig = TcpReplicationConfig
.of(ourAddressAndPort.getPort(), toInetSocketArray(knownHostPorts))
.heartBeatInterval(1, SECONDS).nonUniqueIdentifierListener(identifierListener);
final TcpConfig tcpConfig = TcpConfig
.unknownTopology(ourAddressAndPort.getPort(),
toInetSocketCollection(knownHostPorts))
.heartBeatInterval(1, SECONDS)
.nonUniqueIdentifierListener(identifierListener);
LOG.info("Using Remote identifier=" + identifier);
@@ -231,28 +234,26 @@ public class NodeDiscovery {
return ChronicleMapBuilder.of(Integer.class,
CharSequence.class)
.entries(20000L)
.replicators(identifier, tcpConfig).create();
.replication(identifier, tcpConfig).create();
}
private InetSocketAddress[] toInetSocketArray(Set<AddressAndPort> source) throws
UnknownHostException {
private static Collection<InetSocketAddress> toInetSocketCollection(Set<AddressAndPort> source)
throws UnknownHostException {
// make a safe copy
final HashSet<AddressAndPort> addressAndPorts = new HashSet<AddressAndPort>(source);
if (addressAndPorts.isEmpty())
return new InetSocketAddress[0];
return Collections.emptyList();
final InetSocketAddress[] addresses = new InetSocketAddress[addressAndPorts.size()];
int i = 0;
ArrayList<InetSocketAddress> addresses =
new ArrayList<InetSocketAddress>(addressAndPorts.size());
for (final AddressAndPort addressAndPort : addressAndPorts) {
addresses[i++] = new InetSocketAddress(InetAddress.getByAddress(addressAndPort.address())
.getHostAddress(), addressAndPort.port());
addresses.add(new InetSocketAddress(InetAddress.getByAddress(addressAndPort.address())
.getHostAddress(), addressAndPort.port()));
}
return addresses;
}
@@ -359,7 +360,7 @@ class NodeDiscoveryBroadcaster extends UdpChannelReplicator {
* @throws java.io.IOException
*/
NodeDiscoveryBroadcaster(
final UdpReplicationConfig replicationConfig,
final UdpConfig replicationConfig,
final int serializedEntrySize,
final BytesMarshallable externalizable)
throws IOException {
@@ -25,6 +25,8 @@ public final class OffHeapUpdatableChronicleMapBuilder<K, V>
public static <K, V> OffHeapUpdatableChronicleMapBuilder<K, V> of(
@NotNull Class<K> keyClass, @NotNull Class<V> valueClass) {
if (keyClass != CharSequence.class && keyClass.isInterface())
keyClass = DataValueClasses.directClassFor(keyClass);
if (!offHeapReference(valueClass)) {
if (!valueClass.isInterface()) {
throw new IllegalArgumentException(
@@ -26,7 +26,7 @@ import java.io.Closeable;
/**
* @author Rob Austin.
*/
public interface Replica extends Closeable {
interface Replica extends Closeable {
/**
* Provides the unique Identifier associated with this map instance. <p> An identifier is used to
@@ -19,7 +19,7 @@
package net.openhft.chronicle.map;
import net.openhft.chronicle.hash.TimeProvider;
import net.openhft.chronicle.hash.replication.TimeProvider;
import net.openhft.chronicle.hash.serialization.BytesReader;
import net.openhft.chronicle.hash.serialization.MetaBytesInterop;
import net.openhft.chronicle.hash.serialization.MetaBytesWriter;
@@ -82,7 +82,7 @@ import static net.openhft.lang.collection.DirectBitSet.NOT_FOUND;
* @param <K> the entries key type
* @param <V> the entries value type
*/
class ReplicatedChronicleMap<K, KI, MKI extends MetaBytesInterop<K, KI>,
final class ReplicatedChronicleMap<K, KI, MKI extends MetaBytesInterop<K, KI>,
V, VW, MVW extends MetaBytesWriter<V, VW>>
extends VanillaChronicleMap<K, KI, MKI, V, VW, MVW>
implements ChronicleMap<K, V>,
@@ -102,12 +102,13 @@ class ReplicatedChronicleMap<K, KI, MKI extends MetaBytesInterop<K, KI>,
private transient ModificationDelegator modificationDelegator;
private transient long startOfModificationIterators;
public ReplicatedChronicleMap(@NotNull AbstractChronicleMapBuilder<K, V, ?> builder)
public ReplicatedChronicleMap(@NotNull AbstractChronicleMapBuilder<K, V, ?> builder,
byte identifier)
throws IOException {
super(builder);
this.timeProvider = builder.timeProvider();
this.localIdentifier = builder.identifier();
this.localIdentifier = identifier;
if (localIdentifier == -1) {
throw new IllegalStateException("localIdentifier should not be -1");
@@ -632,8 +633,6 @@ class ReplicatedChronicleMap<K, KI, MKI extends MetaBytesInterop<K, KI>,
V acquireWithoutLock(ThreadLocalCopies copies, MKI metaKeyInterop, KI keyInterop, K key, V usingValue,
long hash2, boolean create, long timestamp) {
long keySize = metaKeyInterop.size(keyInterop, key);
MultiStoreBytes entry = acquireTmpBytes();
long offset = searchKey(keyInterop, metaKeyInterop, key, keySize, hash2, entry,
@@ -19,7 +19,7 @@ package net.openhft.chronicle.map;
import java.io.Closeable;
import java.io.IOException;
public abstract class Replicator {
abstract class Replicator {
/**
* A constructor for use in subclasses.
@@ -16,8 +16,8 @@
package net.openhft.chronicle.map;
import net.openhft.chronicle.hash.TcpReplicationConfig;
import net.openhft.chronicle.hash.UdpReplicationConfig;
import net.openhft.chronicle.hash.replication.TcpConfig;
import net.openhft.chronicle.hash.replication.UdpConfig;
import org.jetbrains.annotations.NotNull;
import java.io.Closeable;
@@ -25,10 +25,18 @@ import java.io.IOException;
final class Replicators {
static final String ONLY_UDP_WARN_MESSAGE =
"MISSING TCP REPLICATION : The UdpReplicator only attempts to read data " +
"(it does not enforce or guarantee delivery), you should use" +
"the UdpReplicator if you have a large number of nodes, and you wish" +
"to receive the data before it becomes available on TCP/IP. Since data" +
"delivery is not guaranteed, it is recommended that you only use" +
"the UDP Replicator in conjunction with a TCP Replicator";
private Replicators() {
}
static Replicator tcp(final TcpReplicationConfig replicationConfig) {
static Replicator tcp(final TcpConfig replicationConfig) {
return new Replicator() {
@Override
@@ -42,16 +50,17 @@ final class Replicators {
.keyBuilder, builder.valueBuilder);
StatelessServerConnector statelessServer = new StatelessServerConnector
(keyValueSerializer, (VanillaChronicleMap) chronicleMap, builder.entrySize());
(keyValueSerializer, (VanillaChronicleMap) chronicleMap,
builder.entrySize(true));
return new TcpReplicator(replica, entryExternalizable, replicationConfig,
builder.entrySize(), statelessServer);
builder.entrySize(true), statelessServer);
}
};
}
static Replicator udp(
final UdpReplicationConfig replicationConfig) {
final UdpConfig replicationConfig) {
return new Replicator() {
@Override
@@ -61,7 +70,7 @@ final class Replicators {
final ChronicleMap chronicleMap)
throws IOException {
return new UdpReplicator(map, entryExternalizable, replicationConfig,
builder.entrySize());
builder.entrySize(true));
}
};
}
@@ -83,18 +83,29 @@ final class SerializationBuilder<E> implements Cloneable {
NullObjectFactory.<E>of();
if (concreteClass(eClass) && Byteable.class.isAssignableFrom(eClass)) {
agileMarshaller(ByteableMarshaller.of((Class) eClass), factory);
ByteableMarshaller agileBytesMarshaller = ByteableMarshaller.of((Class) eClass);
sizeMarshaller(agileBytesMarshaller)
.reader(agileBytesMarshaller, factory)
.interop(agileBytesMarshaller);
} else if (eClass == CharSequence.class || eClass == String.class) {
reader((BytesReader<E>) CharSequenceReader.of(), factory);
writer((BytesWriter<E>) CharSequenceWriter.instance());
} else if (eClass == Void.class) {
agileMarshaller((AgileBytesMarshaller<E>) VoidMarshaller.INSTANCE, factory);
sizeMarshaller(VoidMarshaller.INSTANCE)
.reader((BytesReader<E>) VoidMarshaller.INSTANCE, factory)
.interop((BytesInterop<E>) VoidMarshaller.INSTANCE);
} else if (eClass == Long.class) {
agileMarshaller((AgileBytesMarshaller<E>) LongMarshaller.INSTANCE, factory);
sizeMarshaller(LongMarshaller.INSTANCE)
.reader((BytesReader<E>) LongMarshaller.INSTANCE, factory)
.interop((BytesInterop<E>) LongMarshaller.INSTANCE);
} else if (eClass == Double.class) {
agileMarshaller((AgileBytesMarshaller<E>) DoubleMarshaller.INSTANCE, factory);
sizeMarshaller(DoubleMarshaller.INSTANCE)
.reader((BytesReader<E>) DoubleMarshaller.INSTANCE, factory)
.interop((BytesInterop<E>) DoubleMarshaller.INSTANCE);
} else if (eClass == Integer.class) {
agileMarshaller((AgileBytesMarshaller<E>) IntegerMarshaller.INSTANCE, factory);
sizeMarshaller(IntegerMarshaller.INSTANCE)
.reader((BytesReader<E>) IntegerMarshaller.INSTANCE, factory)
.interop((BytesInterop<E>) IntegerMarshaller.INSTANCE);
} else if (eClass == byte[].class) {
reader((BytesReader<E>) ByteArrayMarshaller.INSTANCE, factory);
interop((BytesInterop<E>) ByteArrayMarshaller.INSTANCE);
@@ -125,14 +136,6 @@ final class SerializationBuilder<E> implements Cloneable {
return this;
}
public SerializationBuilder<E> agileMarshaller(AgileBytesMarshaller<E> agileBytesMarshaller,
ObjectFactory<E> factory) {
if (factory == null) factory = this.factory;
return sizeMarshaller(agileBytesMarshaller)
.reader(agileBytesMarshaller, factory)
.interop(agileBytesMarshaller);
}
public SerializationBuilder<E> interop(BytesInterop<E> interop) {
return copyingInterop(null)
.setInterop(interop)
@@ -142,6 +145,8 @@ final class SerializationBuilder<E> implements Cloneable {
}
public SerializationBuilder<E> writer(BytesWriter<E> writer) {
if (writer instanceof BytesInterop)
return interop((BytesInterop<E>) writer);
return copyingInterop(CopyingInterop.FROM_WRITER)
.setInterop(writer)
.metaInterop(CopyingMetaBytesInterop
@@ -287,10 +292,19 @@ final class SerializationBuilder<E> implements Cloneable {
" value don't use object factory");
} else if (interop instanceof ByteableMarshaller) {
if (factory instanceof AllocateInstanceObjectFactory) {
agileMarshaller(ByteableMarshaller.of((Class) eClass), factory);
ByteableMarshaller agileBytesMarshaller =
ByteableMarshaller.of((Class) eClass);
sizeMarshaller(agileBytesMarshaller)
.reader(agileBytesMarshaller, factory)
.interop(agileBytesMarshaller);
} else {
agileMarshaller(ByteableMarshaller.of((Class) eClass, (ObjectFactory) factory),
factory);
ByteableMarshaller agileBytesMarshaller =
ByteableMarshaller.of((Class) eClass, (ObjectFactory) factory);
ObjectFactory<E> factory1 = factory;
if (factory1 == null) factory1 = this.factory;
sizeMarshaller(agileBytesMarshaller)
.reader(agileBytesMarshaller, factory1)
.interop(agileBytesMarshaller);
}
} else if (interop instanceof BytesMarshallableMarshaller) {
if (factory instanceof AllocateInstanceObjectFactory) {
@@ -19,7 +19,6 @@
package net.openhft.chronicle.map;
import com.sun.jdi.connect.spi.ClosedConnectionException;
import net.openhft.chronicle.hash.StatelessBuilder;
import net.openhft.chronicle.hash.exceptions.IORuntimeException;
import net.openhft.chronicle.hash.exceptions.TimeoutRuntimeException;
import net.openhft.lang.io.ByteBufferBytes;
@@ -61,14 +60,13 @@ class StatelessChronicleMap<K, V> implements ChronicleMap<K, V>, Closeable {
private volatile SocketChannel clientChannel;
private CloseablesManager closeables;
private final StatelessBuilder builder;
private final StatelessMapConfig builder;
private int maxEntrySize;
private final Class<K> kClass;
private final Class<V> vClass;
private final boolean putReturnsNull;
private final boolean removeReturnsNull;
static enum EventId {
HEARTBEAT,
STATEFUL_UPDATE,
@@ -92,20 +90,20 @@ class StatelessChronicleMap<K, V> implements ChronicleMap<K, V>, Closeable {
TO_STRING,
PUT_ALL,
PUT_ALL_WITHOUT_ACC,
HASH_CODE
HASH_CODE,
ACQUIRE_USING
}
private long transactionID;
StatelessChronicleMap(final StatelessBuilder builder,
StatelessChronicleMap(final StatelessMapConfig builder,
final AbstractChronicleMapBuilder chronicleMapBuilder) throws IOException {
this.builder = builder;
this.keyValueSerializer = new KeyValueSerializer<K, V>(chronicleMapBuilder.keyBuilder,
chronicleMapBuilder.valueBuilder);
this.putReturnsNull = chronicleMapBuilder.putReturnsNull();
this.removeReturnsNull = chronicleMapBuilder.removeReturnsNull();
this.maxEntrySize = chronicleMapBuilder.entrySize();
this.maxEntrySize = chronicleMapBuilder.entrySize(false);
this.vClass = chronicleMapBuilder.valueBuilder.eClass;
this.kClass = chronicleMapBuilder.keyBuilder.eClass;
// this.putReturnsNull = putReturnsNull;
@@ -395,6 +393,11 @@ class StatelessChronicleMap<K, V> implements ChronicleMap<K, V>, Closeable {
}
/**
* @param key the key whose associated value is to be returned
* @param usingValue the object to read value data in, if possible
* @return
*/
public synchronized V acquireUsing(K key, V usingValue) {
throw new UnsupportedOperationException("acquireUsing() is not supported for stateless " +
"clients");
@@ -18,8 +18,9 @@
package net.openhft.chronicle.map;
import net.openhft.chronicle.hash.TcpReplicationConfig;
import net.openhft.chronicle.hash.ThrottlingConfig;
import net.openhft.chronicle.hash.replication.IdentifierListener;
import net.openhft.chronicle.hash.replication.TcpConfig;
import net.openhft.chronicle.hash.replication.ThrottlingConfig;
import net.openhft.lang.io.ByteBufferBytes;
import net.openhft.lang.io.Bytes;
import net.openhft.lang.threadlocal.ThreadLocalCopies;
@@ -51,12 +52,12 @@ interface Work {
}
/**
* Used with a {@link net.openhft.chronicle.map.ReplicatedChronicleMap} to send data between the maps using a socket
* connection {@link net.openhft.chronicle.map.TcpReplicator}
* Used with a {@link net.openhft.chronicle.map.ReplicatedChronicleMap} to send data between the
* maps using a socket connection {@link net.openhft.chronicle.map.TcpReplicator}
*
* @author Rob Austin.
*/
public class TcpReplicator extends AbstractChannelReplicator implements Closeable {
final class TcpReplicator extends AbstractChannelReplicator implements Closeable {
public static final int STATELESS_CLIENT = -127;
public static final byte NOT_SET = (byte) HEARTBEAT.ordinal();
@@ -73,7 +74,7 @@ public class TcpReplicator extends AbstractChannelReplicator implements Closeabl
private final byte localIdentifier;
private final int maxEntrySizeBytes;
private final Replica.EntryExternalizable externalizable;
private final TcpReplicationConfig replicationConfig;
private final TcpConfig replicationConfig;
private final StatelessServerConnector statelessServerConnector;
private long selectorTimeout;
@@ -85,11 +86,11 @@ public class TcpReplicator extends AbstractChannelReplicator implements Closeabl
* the entry, but setting it too large reduces the workable
* space in the buffer.
* @param statelessServerConnector set to NULL if not required
* @throws IOException on an io error.
* @throws IOException on an io error.
*/
public TcpReplicator(@NotNull final Replica replica,
@NotNull final Replica.EntryExternalizable externalizable,
@NotNull final TcpReplicationConfig replicationConfig,
@NotNull final TcpConfig replicationConfig,
final int maxEntrySizeBytes,
@Nullable StatelessServerConnector statelessServerConnector) throws IOException {
@@ -278,7 +279,8 @@ public class TcpReplicator extends AbstractChannelReplicator implements Closeabl
}
/**
* check to see if we have lost connection with the remote node and if we have attempts a reconnect.
* check to see if we have lost connection with the remote node and if we have attempts a
* reconnect.
*
* @param key the key relating to the heartbeat that we are checking
* @param approxTimeOutTime the approximate time in milliseconds
@@ -425,8 +427,8 @@ public class TcpReplicator extends AbstractChannelReplicator implements Closeabl
}
/**
* this can be called when a new CHM is added to a cluster, we have to rebootstrap so will clear all the old
* bootstrap information
* this can be called when a new CHM is added to a cluster, we have to rebootstrap so will clear
* all the old bootstrap information
*
* @param key the nio SelectionKey
*/
@@ -438,7 +440,8 @@ public class TcpReplicator extends AbstractChannelReplicator implements Closeabl
}
/**
* used to exchange identifiers and timestamps and heartbeat intervals between the server and client
* used to exchange identifiers and timestamps and heartbeat intervals between the server and
* client
*
* @param key the SelectionKey relating to the this cha
* @param socketChannel
@@ -478,7 +481,8 @@ public class TcpReplicator extends AbstractChannelReplicator implements Closeabl
// this can occur sometimes when if 2 or more remote node attempt to use node discovery at the
// same time
final IdentifierListener identifierListener = replicationConfig.identifierListener;
final IdentifierListener identifierListener =
replicationConfig.nonUniqueIdentifierListener();
final SocketAddress remoteAddress = socketChannel.getRemoteAddress();
@@ -618,9 +622,10 @@ public class TcpReplicator extends AbstractChannelReplicator implements Closeabl
}
/**
* sets interestOps to "selector keys",The change to interestOps much be on the same thread as the selector. This
* class, allows via {@link AbstractChannelReplicator .KeyInterestUpdater#set(int)} to holds a pending change in
* interestOps ( via a bitset ), this change is processed later on the same thread as the selector
* sets interestOps to "selector keys",The change to interestOps much be on the same thread as
* the selector. This class, allows via {@link AbstractChannelReplicator
* .KeyInterestUpdater#set(int)} to holds a pending change in interestOps ( via a bitset ),
* this change is processed later on the same thread as the selector
*/
private static class KeyInterestUpdater {
@@ -651,8 +656,8 @@ public class TcpReplicator extends AbstractChannelReplicator implements Closeabl
}
/**
* @param keyIndex the index of the key that has changed, the list of keys is provided by the constructor {@link
* KeyInterestUpdater(int, SelectionKey[])}
* @param keyIndex the index of the key that has changed, the list of keys is provided by
* the constructor {@link KeyInterestUpdater(int, SelectionKey[])}
*/
public void set(int keyIndex) {
changeOfOpWriteRequired.set(keyIndex);
@@ -893,7 +898,8 @@ public class TcpReplicator extends AbstractChannelReplicator implements Closeabl
}
/**
* writes all the entries that have changed, to the buffer which will later be written to TCP/IP
* writes all the entries that have changed, to the buffer which will later be written to
* TCP/IP
*
* @param modificationIterator a record of which entries have modification
* @param selectionKey
@@ -971,7 +977,8 @@ public class TcpReplicator extends AbstractChannelReplicator implements Closeabl
}
/**
* used to send an single zero byte if we have not send any data for up to the localHeartbeatInterval
* used to send an single zero byte if we have not send any data for up to the
* localHeartbeatInterval
*/
private void writeHeartbeatToBuffer() {
@@ -988,8 +995,8 @@ public class TcpReplicator extends AbstractChannelReplicator implements Closeabl
/**
* removes back in the OP_WRITE from the selector, otherwise it'll spin loop. The OP_WRITE will get added back
* in as soon as we have data to write
* removes back in the OP_WRITE from the selector, otherwise it'll spin loop. The OP_WRITE
* will get added back in as soon as we have data to write
*
* @param socketChannel the socketChannel we wish to stop writing to
* @param attached data associated with the socketChannels key
@@ -1277,6 +1284,7 @@ class StatelessServerConnector<K, V> {
switch (event) {
case LONG_SIZE:
return longSize(reader, writer, sizeLocation);
@@ -1292,6 +1300,10 @@ class StatelessServerConnector<K, V> {
case GET:
return get(reader, writer, sizeLocation);
case ACQUIRE_USING:
return acquireUsing(reader, writer, sizeLocation);
case PUT:
return put(reader, writer, sizeLocation);
@@ -1476,6 +1488,26 @@ class StatelessServerConnector<K, V> {
return null;
}
private Work acquireUsing(Bytes reader, Bytes writer, final long sizeLocation) {
if (MAP_SUPPORTS_BYTES) {
map.acquireUsing(reader, writer);
} else {
final ThreadLocalCopies local = keyValueSerializer.threadLocalCopies();
final K k = readKey(reader, local);
final V v = readValue(reader, local);
try {
writeValue(map.acquireUsing(k, v), writer, local);
} catch (RuntimeException e) {
return sendException(writer, sizeLocation, e);
}
}
writeSizeAndFlags(sizeLocation, false, writer);
return null;
}
private Work get(Bytes reader, Bytes writer, final long sizeLocation) {
if (MAP_SUPPORTS_BYTES) {
map.get(reader, writer);
@@ -18,7 +18,7 @@
package net.openhft.chronicle.map;
import net.openhft.chronicle.hash.UdpReplicationConfig;
import net.openhft.chronicle.hash.replication.UdpConfig;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -69,7 +69,7 @@ class UdpChannelReplicator extends AbstractChannelReplicator implements Replica.
* @param localIdentifier just used for logging
* @throws IOException
*/
UdpChannelReplicator(@NotNull final UdpReplicationConfig replicationConfig,
UdpChannelReplicator(@NotNull final UdpConfig replicationConfig,
final int maxPayloadSize,
final byte localIdentifier)
throws IOException {
@@ -18,7 +18,7 @@
package net.openhft.chronicle.map;
import net.openhft.chronicle.hash.UdpReplicationConfig;
import net.openhft.chronicle.hash.replication.UdpConfig;
import net.openhft.lang.io.ByteBufferBytes;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
@@ -36,14 +36,14 @@ import java.nio.channels.DatagramChannel;
* it becomes available on TCP/IP. In order to not miss data, UdpReplicator should be used in conjunction with
* the TCP Replicator.
*/
public class UdpReplicator extends UdpChannelReplicator implements Replica.ModificationNotifier, Closeable {
final class UdpReplicator extends UdpChannelReplicator implements Replica.ModificationNotifier, Closeable {
private static final Logger LOG =
LoggerFactory.getLogger(UdpReplicator.class.getName());
public UdpReplicator(@NotNull final Replica replica,
@NotNull final Replica.EntryExternalizable entryExternalizable,
@NotNull final UdpReplicationConfig replicationConfig,
@NotNull final UdpConfig replicationConfig,
final int serializedEntrySize)
throws IOException {
@@ -41,7 +41,6 @@ import java.nio.channels.FileChannel;
import java.util.*;
import java.util.concurrent.TimeUnit;
import static java.lang.Long.numberOfTrailingZeros;
import static java.lang.Math.max;
import static java.lang.Thread.currentThread;
import static net.openhft.lang.MemoryUnit.*;
@@ -129,8 +128,8 @@ class VanillaChronicleMap<K, KI, MKI extends MetaBytesInterop<K, KI>,
lockTimeOutNS = builder.lockTimeOut(TimeUnit.NANOSECONDS);
// this.replicas = builder.replicas();
this.entrySize = builder.entrySize();
boolean replicated = getClass() == ReplicatedChronicleMap.class;
this.entrySize = builder.entrySize(replicated);
this.alignment = builder.entryAndValueAlignment();
this.errorListener = builder.errorListener();
@@ -276,19 +275,7 @@ class VanillaChronicleMap<K, KI, MKI extends MetaBytesInterop<K, KI>,
+ sizeOfEntriesInSegment();
if ((ss & 63L) != 0)
throw new AssertionError();
return breakL1CacheAssociativityContention(ss);
}
private long breakL1CacheAssociativityContention(long segmentSize) {
// Conventional alignment to break is 4096 (given Intel's 32KB 8-way L1 cache),
// for any case break 2 times smaller alignment
int alignmentToBreak = 2048;
int eachNthSegmentFallIntoTheSameSet =
max(1, alignmentToBreak >> numberOfTrailingZeros(segmentSize));
if (eachNthSegmentFallIntoTheSameSet < actualSegments) {
segmentSize |= 64L; // make segment size "odd" (in cache lines)
}
return segmentSize;
return ss;
}
int multiMapsPerSegment() {
@@ -597,6 +584,10 @@ class VanillaChronicleMap<K, KI, MKI extends MetaBytesInterop<K, KI>,
throw new UnsupportedOperationException("todo");
}
public V acquireUsing(Bytes reader, Bytes writer) {
throw new UnsupportedOperationException("todo");
}
void get(Bytes reader, Bytes writer) {
throw new UnsupportedOperationException("todo");
}
@@ -1415,8 +1406,7 @@ class VanillaChronicleMap<K, KI, MKI extends MetaBytesInterop<K, KI>,
@Override
public void removeEntry() {
if (copies != null)
removeWithoutLock(copies, metaKeyInterop, keyInterop, key(), null, segmentHash);
removeWithoutLock(copies, metaKeyInterop, keyInterop, key(), null, segmentHash);
}
}
@@ -1430,9 +1420,7 @@ class VanillaChronicleMap<K, KI, MKI extends MetaBytesInterop<K, KI>,
putWithoutLock(copies, metaKeyInterop, keyInterop, key(), value(),
segmentHash, true);
copies = null;
putOnClose = true;
Segment.this.writeUnlock();
}
@@ -21,10 +21,9 @@ package net.openhft.chronicle.map;
* @author Rob Austin.
*/
public interface WriteContext<K, V> extends Context<K, V> {
void dontPutOnClose();
void removeEntry();
// todo I have no idea why we have this, as this will always be done on when calling close()
// void update();
}
@@ -29,7 +29,7 @@ final class ZeroOutValueBytes<K, V> implements PrepareValueBytes<K, V> {
@Override
public void prepare(Bytes bytes, K key) {
long pos = bytes.position();
bytes.zeroOut(pos, pos + valueSize);
bytes.zeroOut(pos, pos + valueSize, true);
bytes.skip(valueSize);
}
}