diff --git a/ReadMe.adoc b/ReadMe.adoc index 1321c28ff..c1a32d637 100644 --- a/ReadMe.adoc +++ b/ReadMe.adoc @@ -3,7 +3,8 @@ Chronicle Software :css-signature: demo :toc: macro :toclevels: 2 -:icons: font +:lang: en-GB +:source-highlighter: rouge image:https://maven-badges.herokuapp.com/maven-central/net.openhft/chronicle-map/badge.svg[caption="",link=https://maven-badges.herokuapp.com/maven-central/net.openhft/chronicle-map] image:https://javadoc.io/badge2/net.openhft/chronicle-map/javadoc.svg[link="https://www.javadoc.io/doc/net.openhft/chronicle-map/latest/index.html"] diff --git a/benchmark/README.adoc b/benchmark/README.adoc index 87f39efd4..27d84f16e 100644 --- a/benchmark/README.adoc +++ b/benchmark/README.adoc @@ -1,7 +1,9 @@ = Benchmark results Peter Lawrey +:lang: en-GB +:source-highlighter: rouge -Summary of results on a Ryzen 9 5950X with a Corsair MP600 driver +Summary of results on a Ryzen 9 5950X with a Corsair MP600 drive == 1 million reads and 1 million writes each second of 500 byte messages @@ -98,4 +100,4 @@ worst: 8896.51 9191.42 9191.42 588251.14 8232.96 ------------------------------------------------------------------------------------------ ``` -NOTE: Running this dataset on a 64 GB machine had lower outliers when run without graphical interface to save some memory and contention. \ No newline at end of file +NOTE: Running this dataset on a 64 GB machine had lower outliers when run without graphical interface to save some memory and contention. diff --git a/checkstyle-suppressions.xml b/checkstyle-suppressions.xml index e1badbb7f..aed5c7a4d 100644 --- a/checkstyle-suppressions.xml +++ b/checkstyle-suppressions.xml @@ -15,4 +15,57 @@ - \ No newline at end of file + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/CM_Compatibility_and_Versioning.adoc b/docs/CM_Compatibility_and_Versioning.adoc index 2cdefa6ae..b1fc20f31 100644 --- a/docs/CM_Compatibility_and_Versioning.adoc +++ b/docs/CM_Compatibility_and_Versioning.adoc @@ -5,6 +5,8 @@ Neil Clifford :css-signature: demo :toc-placement: macro :icons: font +:lang: en-GB +:source-highlighter: rouge toc::[] diff --git a/docs/CM_Download.adoc b/docs/CM_Download.adoc index 5d9cd796b..7ff28c18a 100644 --- a/docs/CM_Download.adoc +++ b/docs/CM_Download.adoc @@ -5,6 +5,8 @@ Neil Clifford :css-signature: demo :toc-placement: macro :icons: font +:lang: en-GB +:source-highlighter: rouge toc::[] diff --git a/docs/CM_FAQs.adoc b/docs/CM_FAQs.adoc index 8cdbc3f5f..9ab5e1a2a 100644 --- a/docs/CM_FAQs.adoc +++ b/docs/CM_FAQs.adoc @@ -5,6 +5,8 @@ Neil Clifford, Peter Lawrey, Rob Austin, Jerry Shea :css-signature: demo :toc-placement: preamble :icons: font +:lang: en-GB +:source-highlighter: rouge This document provides information for some common tasks within Chronicle Map. @@ -91,12 +93,12 @@ This is because Chronicle uses the page cache and RAM is in effect a cache to th There are two cases where having a high-speed disk will give you a real benefit: -==== 1. Data rate +==== Data rate If the rate of data that you are writing exceeds the disk write speed. In most applications this is unlikely to occur. -==== 2. Page cache misses +==== Page cache misses When you get a page cache miss. For Chronicle queues which write and read messages lineally across memory, we mitigate this situation with the use of the Chronicle pre-toucher. diff --git a/docs/CM_Features.adoc b/docs/CM_Features.adoc index 62e15d6df..22289ade2 100644 --- a/docs/CM_Features.adoc +++ b/docs/CM_Features.adoc @@ -5,6 +5,8 @@ Neil Clifford :css-signature: demo :toc-placement: macro :icons: font +:lang: en-GB +:source-highlighter: rouge toc::[] @@ -12,7 +14,7 @@ Chronicle Map is an in-memory, key-value store, designed for low-latency, and/or == Features -- **Ultra low latency**: Chronicle Map targets median latency of both read and write queries of less than 1 microsecond in https://github.com/OpenHFT/Chronicle-Map/search?l=java&q=perf&type=Code[certain tests]. +- **Ultra low latency**: Chronicle Map targets median latency of both read and write queries of less than 1 µs in https://github.com/OpenHFT/Chronicle-Map/search?l=java&q=perf&type=Code[certain tests]. - **High concurrency**: Write queries scale well up to the number of hardware execution threads in the server. Read queries never block each other. @@ -23,7 +25,7 @@ Read queries never block each other. - Multiple processes can access a Chronicle Map concurrently. At the same time, the data store is *in-process* for each of the accessing processes. -Out-of-process approach to IPC is simply incompatible with Chronicle Map's median latency target of < 1 μs. +Out-of-process approach to IPC is simply incompatible with Chronicle Map's median latency target of < 1 µs. - Replication diff --git a/docs/CM_Replication.adoc b/docs/CM_Replication.adoc index 82c58bc3d..a5e78d6bc 100644 --- a/docs/CM_Replication.adoc +++ b/docs/CM_Replication.adoc @@ -6,6 +6,9 @@ Neil Clifford :toc-placement: macro :icons: font +:lang: en-GB +:source-highlighter: rouge + toc::[] == Enterprise Edition diff --git a/docs/CM_Tutorial.adoc b/docs/CM_Tutorial.adoc index 22cd29044..cbda1ebcf 100644 --- a/docs/CM_Tutorial.adoc +++ b/docs/CM_Tutorial.adoc @@ -6,6 +6,9 @@ Neil Clifford :toc-placement: macro :icons: font +:lang: en-GB +:source-highlighter: rouge + toc::[] This document describes the Chronicle Map tutorial supplied with the project. diff --git a/docs/CM_Tutorial_Behaviour.adoc b/docs/CM_Tutorial_Behaviour.adoc index d8a1f445a..a3a33f0b5 100644 --- a/docs/CM_Tutorial_Behaviour.adoc +++ b/docs/CM_Tutorial_Behaviour.adoc @@ -6,6 +6,9 @@ Neil Clifford :toc-placement: macro :icons: font +:lang: en-GB +:source-highlighter: rouge + toc::[] == Customization @@ -333,4 +336,3 @@ System.out.println(map2.get("1")); ''' <> - diff --git a/docs/CM_Tutorial_Bytes.adoc b/docs/CM_Tutorial_Bytes.adoc index 93b09d042..b3cefb260 100644 --- a/docs/CM_Tutorial_Bytes.adoc +++ b/docs/CM_Tutorial_Bytes.adoc @@ -6,6 +6,9 @@ Neil Clifford :toc-placement: macro :icons: font +:lang: en-GB +:source-highlighter: rouge + toc::[] This pair of interfaces is configured using `ChronicleMapBuilder.keyMarshallers()` or diff --git a/docs/CM_Tutorial_DataAccess.adoc b/docs/CM_Tutorial_DataAccess.adoc index 2a1cb4918..aa44f1d3f 100644 --- a/docs/CM_Tutorial_DataAccess.adoc +++ b/docs/CM_Tutorial_DataAccess.adoc @@ -6,6 +6,9 @@ Neil Clifford :toc-placement: macro :icons: font +:lang: en-GB +:source-highlighter: rouge + toc::[] This pair of interfaces is configured using `ChronicleMapBuilder.keyReaderAndDataAccess()` or @@ -166,4 +169,4 @@ NOTE: If you configure `byte[]` key, or value type, then this pair of serializer ''' -<> \ No newline at end of file +<> diff --git a/docs/CM_Tutorial_Sized.adoc b/docs/CM_Tutorial_Sized.adoc index 7317719ea..37af36d6e 100644 --- a/docs/CM_Tutorial_Sized.adoc +++ b/docs/CM_Tutorial_Sized.adoc @@ -6,6 +6,9 @@ Neil Clifford :toc-placement: macro :icons: font +:lang: en-GB +:source-highlighter: rouge + toc::[] This pair of interfaces is configured using `ChronicleMapBuilder.keyMarshallers()` or diff --git a/docs/CM_Tutorial_Understanding.adoc b/docs/CM_Tutorial_Understanding.adoc index c3e40948a..8ee4c4553 100644 --- a/docs/CM_Tutorial_Understanding.adoc +++ b/docs/CM_Tutorial_Understanding.adoc @@ -6,6 +6,9 @@ Neil Clifford :toc-placement: macro :icons: font +:lang: en-GB +:source-highlighter: rouge + toc::[] == Problems diff --git a/docs/CM_Updates.adoc b/docs/CM_Updates.adoc index b475d69df..c6e0bf427 100644 --- a/docs/CM_Updates.adoc +++ b/docs/CM_Updates.adoc @@ -6,6 +6,9 @@ Neil Clifford :toc-placement: macro :icons: font +:lang: en-GB +:source-highlighter: rouge + toc::[] Changes between Chronicle Map 3 and the previous Chronicle Map version are detailed below: diff --git a/docs/systemProperties.adoc b/docs/systemProperties.adoc new file mode 100644 index 000000000..daabd2159 --- /dev/null +++ b/docs/systemProperties.adoc @@ -0,0 +1,47 @@ += Chronicle Map System Properties +:toc: +:lang: en-GB +:source-highlighter: rouge + +== System Properties + +This document lists system properties that influence Chronicle Map behaviour in production and test runs. +Set each property on the Java command line using `-Dkey=value`. + +NOTE: Unless otherwise stated, boolean properties are parsed via Chronicle Core's `Jvm.getBoolean` helper. +They are treated as enabled if the key is present with no value, `true` or `yes`. + +.System properties +[cols="2a,1,3a,2a",options="header"] +|=== +| Property Key +| Default Value +| Description +| Java Variable Name (Type) + +| `chronicle.map.creation.debug` +| `false` +| Enables verbose logging during Chronicle Map creation and recovery, including map name, file paths and configuration details. Useful when diagnosing startup issues and misconfigured builders. +| `MAP_CREATION_DEBUG` (`boolean`) + +| `chronicle.map.file.lock.timeout.secs` +| `10` +| Number of seconds Chronicle Map waits when acquiring an internal file lock before giving up and throwing a lock related exception. +| `FILE_LOCK_TIMEOUT` (`int`) + +| `chronicle.map.sparseFile` +| `false` +| When `true`, Chronicle Map uses sparse files for persisted data. This can reduce disk usage on some file systems at the cost of more fragmented allocation patterns. +| `sparseFile` (`boolean`) + +| `chronicle.map.disable.locking` +| `false` +| Disables Chronicle Map file locking. When `true`, shared and exclusive locks are not acquired, which may be required on platforms without reliable file locking but removes protection against concurrent writers. +| `USE_EXCLUSIVE_LOCKING`, `USE_SHARED_LOCKING` (derived `boolean` flags) + +| `net.openhft.chronicle.map.lockTimeoutSeconds` +| `60` +| Overrides the global timeout, in seconds, used when waiting for segment level locks in multi-process use. If this timeout is exceeded an `InterProcessDeadLockException` is thrown with guidance on possible causes. +| `LOCK_TIMEOUT_SECONDS` (`int`) +|=== + diff --git a/pom.xml b/pom.xml index 38ec124e0..b2cd75824 100644 --- a/pom.xml +++ b/pom.xml @@ -33,7 +33,7 @@ net.openhft third-party-bom - 3.27ea5 + 3.27ea7 pom import @@ -330,7 +330,6 @@ **/Compiled*.java false - -Xdoclint:none diff --git a/spec/3_2-lock-structure.md b/spec/3_2-lock-structure.md index 83ed46d79..f14800994 100644 --- a/spec/3_2-lock-structure.md +++ b/spec/3_2-lock-structure.md @@ -106,10 +106,6 @@ procedure and call one depending on the context. > The reference Java implementation uses only the version of this procedure without the first two > steps. - - - - ## Release write lock, or write to update lock downgrade, or write to read lock downgrade Perform a CAS operation on the count word of the lock state, comparing 0x80000000 (i. e. a count @@ -141,9 +137,6 @@ procedure. read with a wait word with the wait count decremented. If the CAS operation fails, begin the deregister wait procedure from the start. If the CAS operation succeeds, the procedure succeeds. - - - ## Time-limited write lock acquisition or update to write upgrade 1. Perform the corresponding *try acquire* procedure ([write lock](#try-acquire-write-lock) or diff --git a/spec/4-hashing-algorithms.md b/spec/4-hashing-algorithms.md index 70d3f9a5f..34a98ae43 100644 --- a/spec/4-hashing-algorithms.md +++ b/spec/4-hashing-algorithms.md @@ -6,9 +6,9 @@ the primary key hash code. Then the [`hashSplitting`](3_1-header-fields.md#hashs is applied, to determine the segment in which the key should be stored, and the part of the key hash code to be stored in a segment tier's hash lookup. -> The reference Java implementation: [`XxHash_r39`]( -> https://github.com/OpenHFT/Chronicle-Algorithms/blob/chronicle-algorithms-1.1.6/src/main/java/net/openhft/chronicle/algo/hashing/XxHash_r39.java). -> Although the Java implementation class has `_r39` suffix, the xxHash algorithm is stable since r3 +> The reference Java implementation: [`XxHashR39`]( +> https://github.com/OpenHFT/Chronicle-Algorithms/blob/chronicle-algorithms-1.1.6/src/main/java/net/openhft/chronicle/algo/hashing/XxHashR39.java). +> Although the algorithm originated from the r39 release, the xxHash algorithm is stable since r3 > and [won't change in the future]( > https://github.com/Cyan4973/xxHash/issues/34#issuecomment-169176338). A different version of > the algorithm could have a different name. @@ -62,4 +62,4 @@ checksum](#primary-checksum). The entry checksum is stored in the 6th field of t structure](3-memory-layout.md#stored-entry-structure). > The reference Java implementation: [`HashEntryChecksumStrategy`]( -> ../src/main/java/net/openhft/chronicle/hash/impl/stage/entry/HashEntryChecksumStrategy.java). \ No newline at end of file +> ../src/main/java/net/openhft/chronicle/hash/impl/stage/entry/HashEntryChecksumStrategy.java). diff --git a/src/main/docs/architecture-overview.adoc b/src/main/docs/architecture-overview.adoc new file mode 100644 index 000000000..41c9fc771 --- /dev/null +++ b/src/main/docs/architecture-overview.adoc @@ -0,0 +1,49 @@ += Chronicle Map Architecture Overview +:toc: +:sectnums: +:lang: en-GB +:source-highlighter: rouge + +This document provides a high-level overview of Chronicle Map, its role in the Chronicle stack, and the main design choices that underpin its behaviour. +It complements the existing user guides in `docs/CM_*.adoc` and will be extended as further ISO 9001 and 27001 work is performed. + +== Context and Role + +Chronicle Map is an off-heap, persisted key–value store designed for low-latency access and inter-process data sharing. +It sits in Layer 1 of the Chronicle stack alongside Chronicle Queue and Chronicle Wire and is typically used by higher-level services to cache, share and replicate state. + +Chronicle Map depends on: + +* Chronicle Bytes for off-heap and memory-mapped storage primitives. +* Chronicle Core for utilities, lifecycle handling and configuration helpers. +* Chronicle Threads for optional background maintenance and monitoring tasks. +* Chronicle Wire for serialising complex keys and values when needed. + +== Core Abstractions + +The primary runtime abstractions are: + +* `ChronicleMap` – the main key–value container interface, usually created via `ChronicleMapBuilder`. +* `ChronicleMapBuilder` – a fluent builder that configures key and value types, expected entry count, persistence location and replication parameters. +* Query contexts – `ExternalMapQueryContext` and related types that provide scoped, allocation-aware access to entries. +* Event listeners – hooks such as `MapEventListener` used to observe updates and replication events. + +Maps may be in-heap or persisted; persisted instances back their entries with memory-mapped files so that multiple JVMs or processes can observe the same data structures. + +== Storage and Persistence Model + +Chronicle Map uses fixed-size segments and off-heap memory to store entries. +When persistence is enabled, segments are backed by memory-mapped files so that data survives process restarts and can be shared between JVMs. + +Key aspects include: + +* off-heap storage avoids GC pauses on large maps; +* segments can be accessed concurrently by multiple threads, subject to the configured locking strategy; +* file-backed maps require careful coordination around file-system permissions and lifecycle, as described in the existing `CM_*.adoc` guides. + +Further details on wire formats, replication and compatibility are available in: + +* `docs/CM_Compatibility_and_Versioning.adoc` +* `docs/CM_Replication.adoc` +* `docs/CM_Tutorial_*.adoc` + diff --git a/src/main/docs/decision-log.adoc b/src/main/docs/decision-log.adoc new file mode 100644 index 000000000..262d887d3 --- /dev/null +++ b/src/main/docs/decision-log.adoc @@ -0,0 +1,56 @@ += Chronicle Map Decision Log +:toc: +:sectnums: +:lang: en-GB +:source-highlighter: rouge + +This file captures component-specific architectural and operational decisions for Chronicle Map. +Identifiers follow the `--NNN` pattern with scope `MAP` (Chronicle Map) and Nine-Box tags where practical. + +== Decision Index + +* link:#MAP-FN-101[MAP-FN-101 Off-heap Segmented Hash Map Design] +* link:#MAP-NF-O-201[MAP-NF-O-201 Sizing and Capacity Configuration Via Builder] + +[[MAP-FN-101]] +== MAP-FN-101 Off-heap Segmented Hash Map Design + +Date:: 2025-11-18 +Context:: +* Chronicle Map must support very large maps that may not fit in on-heap memory. +* Many users require persistence and inter-process sharing via memory-mapped files. +Decision Statement:: +* Chronicle Map uses an off-heap segmented hash map design backed by memory-mapped files, allowing entries to be stored outside the Java heap while remaining addressable via the `ChronicleMap` API. +Alternatives Considered:: +* Pure on-heap `ConcurrentHashMap`-style implementation – simple but unable to scale to tens of gigabytes of data or share state between processes. +* Flat file or database-backed key–value store – would introduce higher latency and require different APIs from existing Chronicle components. +Rationale for Decision:: +* Off-heap segments and memory-mapped backing allow large maps with predictable latency while retaining a familiar Java API. +* The design aligns with Chronicle's focus on low-latency, garbage-lean data structures. +Impact & Consequences:: +* Users must size maps explicitly and consider off-heap memory and file-system limits. +* Requirements such as `MAP-FN-001` and `MAP-FN-002` and the sizing guidance in `project-requirements.adoc` follow from this design. +Notes/Links:: +* link:project-requirements.adoc[Project Requirements] + +[[MAP-NF-O-201]] +== MAP-NF-O-201 Sizing and Capacity Configuration Via Builder + +Date:: 2025-11-18 +Context:: +* Incorrect sizing of Chronicle Map (for example too few entries or segments) can lead to performance degradation or capacity errors in production. +* Operators need a clear and supported way to configure sizing without relying on defaults. +Decision Statement:: +* Chronicle Map exposes sizing and capacity configuration via the fluent `ChronicleMapBuilder`, including expected entry count and average key/value sizes; operators are expected to use these builder settings rather than relying on implicit defaults. +Alternatives Considered:: +* Hidden heuristics that infer sizing from early usage – convenient but unpredictable and difficult to document. +* Hard-coded sizes – simple but unsuitable for the range of map sizes and workloads Chronicle Map targets. +Rationale for Decision:: +* Builder-based sizing makes sizing decisions explicit in code and documentation. +* It enables operational guidance and testing (for example `EntryCountMapTest`, `AutoResizeTest`, `KeySegmentDistributionTest`) to focus on a small set of well-defined parameters. +Impact & Consequences:: +* Application code and tutorials must show correct builder usage. +* Operational run-books and examples in `docs/CM_Tutorial_*.adoc` can give concrete sizing recipes. +Notes/Links:: +* link:project-requirements.adoc[Project Requirements] + diff --git a/src/main/docs/project-requirements.adoc b/src/main/docs/project-requirements.adoc new file mode 100644 index 000000000..f8e9e40ea --- /dev/null +++ b/src/main/docs/project-requirements.adoc @@ -0,0 +1,81 @@ += Chronicle Map Project Requirements +:toc: +:sectnums: +:lang: en-GB +:source-highlighter: rouge + +== Scope + +Chronicle Map provides an off-heap, optionally persisted key–value store with support for inter-process sharing and replication. +The requirements in this document summarise existing behaviour described in the `docs/CM_*.adoc` guides and will be refined in future ISO-alignment passes. + +== Functional Requirements (Initial Skeleton) + +[cols=\"1,5,4\",options=\"header\"] +|=== +|ID |Requirement |Verification +|MAP-FN-001 |Provide an off-heap key–value store addressable via `ChronicleMap` that supports put/get/remove operations with predictable latency. |Core map behaviour is exercised by tests such as `ChronicleMapImportExportTest`, `SerializableTest`, `EntryCountMapTest`, `KeySizesTest` and `HugeSparseMapTest`, together with tutorial code under `docs/CM_Tutorial_*.adoc`. +|MAP-FN-002 |Support persisted maps backed by memory-mapped files so that data survives JVM restarts and can be shared between processes. |Persistence and restart scenarios are covered by tests such as `ChronicleMapImportExportTest`, `BasicReplicationTest`, `AutoResizeTest` and long-running examples such as `LargeMapMain`. +|MAP-FN-003 |Expose a fluent `ChronicleMapBuilder` to configure key/value types, expected entry count and persistence settings. |Builder usage examples in `docs/CM_Tutorial_DataAccess.adoc` and tests such as `EntryCountMapTest`, `BytesMarshallableValueTest` and `ChronicleSetBuilderTest` (for the related Chronicle Set builder). +|=== + +== Non-Functional Requirements - Performance + +[cols=\"1,5,4\",options=\"header\"] +|=== +|ID |Requirement |Verification +|MAP-NF-P-001 |Put and get operations on typical maps (with configured average key and value sizes) should maintain predictable latency across supported entry-count ranges. |Micro-benchmarks and tests such as `CHMLatencyTestMain` and `PageLatencyMain` measure latency characteristics under different map sizes and access patterns; results are used to detect regressions. +|MAP-NF-P-002 |Replicated Chronicle Maps should maintain acceptable end-to-end latency for update propagation across typical cluster topologies. |Replication-oriented tests such as `BasicReplicationTest` exercise update propagation between maps; additional benchmarks may be added to characterise latency across nodes. +|=== + +== Non-Functional Requirements - Operability + +[cols=\"1,5,4\",options=\"header\"] +|=== +|ID |Requirement |Verification +|MAP-NF-O-001 |Chronicle Map should provide configuration options and documented patterns for sizing (entry count and segment count) so operators can avoid unexpected resizing or capacity errors in production. |Examples and guidance in `docs/CM_Tutorial_DataAccess.adoc` and related guides, together with tests such as `EntryCountMapTest`, `AutoResizeTest` and `KeySegmentDistributionTest`, illustrate how sizing parameters affect behaviour. +|=== + +== Non-Functional Requirements - Security + +[cols=\"1,5,4\",options=\"header\"] +|=== +|ID |Requirement |Verification +|MAP-NF-S-001 |Chronicle Map must rely on Chronicle Bytes and related core libraries for bounds-checked off-heap access and avoid unchecked direct memory writes that could corrupt map metadata or entries; security-sensitive use (for example maps storing secrets) is expected to layer encryption and access control externally. |Code reviews and static analysis focus on memory-access paths in Chronicle Map, ensuring they pass through Chronicle Bytes safety checks; higher-level security guidance is provided by the Chronicle Bytes and Chronicle Queue security reviews and by deployment documentation in the wider stack. +|=== + +== Traceability and Future Work + +The tables above provide an initial mapping from `MAP-*` requirements to representative tests and examples. +They focus on the most widely used Chronicle Map behaviours; additional requirements and associated tests can be added as further behaviours are formalised. + +[cols=\"1,5,4\",options=\"header\"] +|=== +|Requirement ID |Representative tests |Notes + +|MAP-FN-001 +|`ChronicleMapImportExportTest`, `SerializableTest`, `EntryCountMapTest`, `KeySizesTest`, `HugeSparseMapTest` +|Exercise basic off-heap key–value operations, serialisation, sizing and distribution across segments. + +|MAP-FN-002 +|`ChronicleMapImportExportTest`, `BasicReplicationTest`, `AutoResizeTest`, `LargeMapMain` +|Cover persisted maps backed by memory-mapped files, restart scenarios, replication between processes and resizing behaviour. + +|MAP-FN-003 +|`EntryCountMapTest`, `BytesMarshallableValueTest`, `ChronicleSetBuilderTest` +|Use `ChronicleMapBuilder` (and related builder patterns) to configure entry counts, key/value types and persistence, verifying that builder options are honoured. + +|MAP-NF-P-001, MAP-NF-P-002 +|`CHMLatencyTestMain`, `PageLatencyMain`, `BasicReplicationTest` +|Provide latency measurements for local and replicated maps; used to monitor performance regressions. + +|MAP-NF-O-001 +|`EntryCountMapTest`, `AutoResizeTest`, `KeySegmentDistributionTest` +|Demonstrate the impact of sizing and segment configuration on behaviour, helping operators tune maps for production. +|=== + +Future work should: + +* expand the requirements catalogue as additional behaviours are formalised; +* align existing `CM_*` documentation with the `MAP-*` identifiers above and add further `MAP-NF-S-*` and `MAP-NF-O-*` entries for security and operability; +* keep the mapping between `MAP-*` requirements and representative tests in sync with the evolving test suite. diff --git a/src/main/docs/testing-strategy.adoc b/src/main/docs/testing-strategy.adoc new file mode 100644 index 000000000..278767b87 --- /dev/null +++ b/src/main/docs/testing-strategy.adoc @@ -0,0 +1,48 @@ += Chronicle Map Testing Strategy +:toc: +:sectnums: +:lang: en-GB +:source-highlighter: rouge + +This document outlines how Chronicle Map is tested. +It complements the `MAP-*` requirements in `project-requirements.adoc` and helps reviewers understand how key behaviours are validated. + +== Objectives + +Testing for Chronicle Map aims to: + +* verify the functional requirements (`MAP-FN-*`) for core map operations, persistence and builder configuration; +* exercise non-functional requirements (`MAP-NF-P-*`, `MAP-NF-O-*`) around latency, sizing and operability; +* ensure that off-heap and persisted maps behave correctly across JVM restarts and, where applicable, in replicated deployments. + +== Unit and Integration Tests + +Representative tests include: + +* core operations and serialisation: `ChronicleMapImportExportTest`, `SerializableTest`, `BytesMarshallableValueTest`; +* sizing and distribution: `EntryCountMapTest`, `KeySizesTest`, `HugeSparseMapTest`, `KeySegmentDistributionTest`; +* persistence and restart: `ChronicleMapImportExportTest`, `AutoResizeTest`, examples such as `LargeMapMain`; +* replication: `BasicReplicationTest` and related classes under `net.openhft.chronicle.map`. + +These tests are organised under `src/test/java` and are run via the standard Maven test lifecycle. + +== Performance and Latency Tests + +Latency characteristics for Chronicle Map are explored using tests and harnesses such as: + +* `CHMLatencyTestMain` – exercises map operations under load and reports latency metrics; +* `PageLatencyMain` – explores page and memory-mapped access patterns. + +These programmes are typically run manually or in dedicated performance environments rather than on every CI build, but they inform the performance expectations captured in `MAP-NF-P-*` requirements. + +== Traceability + +`project-requirements.adoc` documents the `MAP-*` requirements and includes a traceability table mapping each requirement to representative tests. +When new behaviours are added or existing ones change, keep the following aligned: + +* add or update `MAP-*` entries in `project-requirements.adoc`; +* extend the traceability table with the relevant test classes; +* add or update unit, integration or performance tests under `src/test/java`. + +All tests should pass under the shared quality profiles on supported JDKs before releasing new versions of Chronicle Map. + diff --git a/src/main/java/net/openhft/chronicle/hash/impl/stage/data/bytes/InputKeyBytesData.java b/src/main/java/net/openhft/chronicle/hash/impl/stage/data/bytes/InputKeyBytesData.java index 1f996a83e..889de8925 100644 --- a/src/main/java/net/openhft/chronicle/hash/impl/stage/data/bytes/InputKeyBytesData.java +++ b/src/main/java/net/openhft/chronicle/hash/impl/stage/data/bytes/InputKeyBytesData.java @@ -18,7 +18,6 @@ */ package net.openhft.chronicle.hash.impl.stage.data.bytes; -import net.openhft.chronicle.bytes.Bytes; import net.openhft.chronicle.bytes.BytesStore; import net.openhft.chronicle.bytes.RandomDataInput; import net.openhft.chronicle.bytes.VanillaBytes; diff --git a/src/main/java/net/openhft/chronicle/hash/impl/util/FileIOUtils.java b/src/main/java/net/openhft/chronicle/hash/impl/util/FileIOUtils.java index 909e0a33d..3f30fc531 100644 --- a/src/main/java/net/openhft/chronicle/hash/impl/util/FileIOUtils.java +++ b/src/main/java/net/openhft/chronicle/hash/impl/util/FileIOUtils.java @@ -3,6 +3,8 @@ */ package net.openhft.chronicle.hash.impl.util; +import net.openhft.chronicle.core.Jvm; + import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; @@ -17,10 +19,21 @@ public static void readFully(FileChannel fileChannel, long filePosition, ByteBuf int startBufferPosition = buffer.position(); while (buffer.remaining() > 0 && buffer.position() < fileChannel.size()) { - int bytesRead = fileChannel.read(buffer, - filePosition + buffer.position() - startBufferPosition); - if (bytesRead == -1) - break; + long position = filePosition + buffer.position() - startBufferPosition; + try { + int bytesRead = fileChannel.read(buffer, position); + if (bytesRead == -1) + break; + } catch (IOException e) { + Jvm.warn().on(FileIOUtils.class, "IOException in readFully: " + + "fileChannel: " + fileChannel + + ", position= " + position + + ", filePosition=" + filePosition + + ", buffer.position()=" + buffer.position() + + ", buffer.remaining()=" + buffer.remaining() + + ", startBufferPosition=" + startBufferPosition, e); + throw e; + } } } @@ -28,7 +41,19 @@ public static void writeFully(FileChannel fileChannel, long filePosition, ByteBu throws IOException { int startBufferPosition = buffer.position(); while (buffer.remaining() > 0) { - fileChannel.write(buffer, filePosition + buffer.position() - startBufferPosition); + long position = filePosition + buffer.position() - startBufferPosition; + try { + fileChannel.write(buffer, position); + } catch (IOException ioe) { + Jvm.warn().on(FileIOUtils.class, "IOException in writeFully: " + + "fileChannel: " + fileChannel + + ", position= " + position + + ", filePosition=" + filePosition + + ", buffer.position()=" + buffer.position() + + ", buffer.remaining()=" + buffer.remaining() + + ", startBufferPosition=" + startBufferPosition, ioe); + throw ioe; + } } } } diff --git a/src/main/java/net/openhft/chronicle/hash/serialization/impl/ByteBufferDataAccess.java b/src/main/java/net/openhft/chronicle/hash/serialization/impl/ByteBufferDataAccess.java index 57c76ab76..477747495 100644 --- a/src/main/java/net/openhft/chronicle/hash/serialization/impl/ByteBufferDataAccess.java +++ b/src/main/java/net/openhft/chronicle/hash/serialization/impl/ByteBufferDataAccess.java @@ -3,7 +3,6 @@ */ package net.openhft.chronicle.hash.serialization.impl; -import net.openhft.chronicle.bytes.Bytes; import net.openhft.chronicle.bytes.BytesStore; import net.openhft.chronicle.bytes.RandomDataInput; import net.openhft.chronicle.bytes.VanillaBytes; diff --git a/src/main/java/net/openhft/chronicle/map/AbstractChronicleMap.java b/src/main/java/net/openhft/chronicle/map/AbstractChronicleMap.java index e5b40912f..94db5fc6a 100644 --- a/src/main/java/net/openhft/chronicle/map/AbstractChronicleMap.java +++ b/src/main/java/net/openhft/chronicle/map/AbstractChronicleMap.java @@ -82,7 +82,7 @@ default Collection values() { @Override public Iterator iterator() { return new Iterator() { - private Iterator> i = entrySet().iterator(); + private final Iterator> i = entrySet().iterator(); @Override public boolean hasNext() { diff --git a/src/main/java/net/openhft/chronicle/map/ChronicleMap.java b/src/main/java/net/openhft/chronicle/map/ChronicleMap.java index fd6684c4b..01297b150 100644 --- a/src/main/java/net/openhft/chronicle/map/ChronicleMap.java +++ b/src/main/java/net/openhft/chronicle/map/ChronicleMap.java @@ -164,8 +164,8 @@ static ChronicleMapBuilder of(Class keyClass, Class valueClas * * @param key the key whose associated value is to be returned * @param usingValue the object to read value data in, if present. Can be null - * @see #acquireUsing(Object, Object) * @return Lock control object that releases the update lock on close. + * @see #acquireUsing(Object, Object) */ @NotNull net.openhft.chronicle.core.io.Closeable acquireContext(@NotNull K key, @NotNull V usingValue); @@ -237,6 +237,7 @@ static ChronicleMapBuilder of(Class keyClass, Class valueClas * @return the amount of free space in the map as a percentage. When the free space gets low ( around 5-25% ) the map will automatically expand. The * number of times it can automatically expand is based on the {@code net.openhft.chronicle.map.ChronicleMapBuilder#maxBloatFactor}. If the map * expands you will see an increase in the available free space. NOTE: It is not possible to expand the chronicle map manually. + * * @see net.openhft.chronicle.map.ChronicleMap#remainingAutoResizes as these operations are related. */ default short percentageFreeSpace() { @@ -245,6 +246,7 @@ default short percentageFreeSpace() { /** * WARNING: This is a detailed however expensive operation which can take milliseconds + * * @return an array of how full each segment is */ default SegmentStats[] segmentStats() { diff --git a/src/main/java/net/openhft/chronicle/map/ChronicleMapBuilder.java b/src/main/java/net/openhft/chronicle/map/ChronicleMapBuilder.java index db0501e83..8db15f774 100644 --- a/src/main/java/net/openhft/chronicle/map/ChronicleMapBuilder.java +++ b/src/main/java/net/openhft/chronicle/map/ChronicleMapBuilder.java @@ -1763,7 +1763,7 @@ private ChronicleMap createWithFile(@NotNull final File file, } } - private void prepareMapPublication(@NotNull final VanillaChronicleMap map) throws IOException { + private void prepareMapPublication(@NotNull final VanillaChronicleMap map) { establishReplication(map); map.setResourcesName(); map.registerCleaner(); @@ -1969,7 +1969,7 @@ private ChronicleMap createWithoutFile() { } @SuppressWarnings("unchecked") - private VanillaChronicleMap newMap() throws IOException { + private VanillaChronicleMap newMap() { preMapConstruction(); if (replicated) { try { diff --git a/src/main/java/net/openhft/chronicle/map/FindByName.java b/src/main/java/net/openhft/chronicle/map/FindByName.java index dd09e697d..3f085acab 100644 --- a/src/main/java/net/openhft/chronicle/map/FindByName.java +++ b/src/main/java/net/openhft/chronicle/map/FindByName.java @@ -5,9 +5,6 @@ import net.openhft.chronicle.hash.ChronicleHash; -import java.io.IOException; -import java.util.concurrent.TimeoutException; - /** * @author Rob Austin. */ @@ -19,10 +16,6 @@ interface FindByName { * @param the type returned * @return a chronicle map or set * @throws IllegalArgumentException if a map with this name can not be found - * @throws IOException if it not possible to create the map or set - * @throws TimeoutException if the call times out - * @throws InterruptedException if interrupted by another thread */ - T from(String name) throws IllegalArgumentException, - IOException, TimeoutException, InterruptedException; + T from(String name) throws IllegalArgumentException; } diff --git a/src/main/java/net/openhft/chronicle/map/JsonSerializer.java b/src/main/java/net/openhft/chronicle/map/JsonSerializer.java index 46e45db69..3a055051c 100644 --- a/src/main/java/net/openhft/chronicle/map/JsonSerializer.java +++ b/src/main/java/net/openhft/chronicle/map/JsonSerializer.java @@ -10,6 +10,7 @@ import net.openhft.xstream.converters.*; import java.io.*; +import java.nio.file.Files; import java.util.List; import java.util.Map; import java.util.zip.GZIPInputStream; @@ -59,16 +60,16 @@ static synchronized void putAll(final File fromFile, private static InputStream createInputStream(final File toFile) throws IOException { if (toFile.getName().toLowerCase().endsWith(".gz")) - return new GZIPInputStream(new FileInputStream(toFile)); + return new GZIPInputStream(Files.newInputStream(toFile.toPath())); else - return new FileInputStream(toFile); + return Files.newInputStream(toFile.toPath()); } private static OutputStream createOutputStream(final File toFile) throws IOException { if (toFile.getName().toLowerCase().endsWith(".gz")) - return new GZIPOutputStream(new FileOutputStream(toFile)); + return new GZIPOutputStream(Files.newOutputStream(toFile.toPath())); else - return new FileOutputStream(toFile); + return Files.newOutputStream(toFile.toPath()); } private static XStream xStream(final Map map, final List jsonConverters) { diff --git a/src/main/java/net/openhft/chronicle/map/OldDeletedEntriesCleanupThread.java b/src/main/java/net/openhft/chronicle/map/OldDeletedEntriesCleanupThread.java index 8db260682..ec7a06e1a 100644 --- a/src/main/java/net/openhft/chronicle/map/OldDeletedEntriesCleanupThread.java +++ b/src/main/java/net/openhft/chronicle/map/OldDeletedEntriesCleanupThread.java @@ -54,7 +54,7 @@ class OldDeletedEntriesCleanupThread extends Thread private long prevSegment0ScanStart = -1; private long removedCompletely; - private long startTime = System.currentTimeMillis(); + private final long startTime = System.currentTimeMillis(); OldDeletedEntriesCleanupThread(ReplicatedChronicleMap map) { super("Cleanup Thread for " + map.toIdentityString()); diff --git a/src/main/java/net/openhft/chronicle/map/ReplicatedChronicleMap.java b/src/main/java/net/openhft/chronicle/map/ReplicatedChronicleMap.java index 32efec556..d4e7d17ad 100644 --- a/src/main/java/net/openhft/chronicle/map/ReplicatedChronicleMap.java +++ b/src/main/java/net/openhft/chronicle/map/ReplicatedChronicleMap.java @@ -26,7 +26,6 @@ import net.openhft.chronicle.wire.WireOut; import org.jetbrains.annotations.NotNull; -import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; @@ -121,7 +120,7 @@ public class ReplicatedChronicleMap extends VanillaChronicleMap builder) throws IOException { + public ReplicatedChronicleMap(@NotNull final ChronicleMapBuilder builder) { super(builder); tierModIterBitSetSizeInBits = computeTierModIterBitSetSizeInBits(); tierModIterBitSetOuterSize = computeTierModIterBitSetOuterSize(); diff --git a/src/main/java/net/openhft/chronicle/map/VanillaChronicleMap.java b/src/main/java/net/openhft/chronicle/map/VanillaChronicleMap.java index ab3d85b13..80a2902c4 100644 --- a/src/main/java/net/openhft/chronicle/map/VanillaChronicleMap.java +++ b/src/main/java/net/openhft/chronicle/map/VanillaChronicleMap.java @@ -80,7 +80,7 @@ public class VanillaChronicleMap ///////////////////////////////////////////////// private transient String name; /** - * identityString is initialized lazily in {@link #toIdentityString()} rather than in {@link #initOwnTransients()} because it depends on {@link + * identityString is initialized lazily in {@link #toIdentityString()} rather than in because it depends on {@link * #file()} which is set after initOwnTransients(). */ private transient String identityString; diff --git a/src/main/java/net/openhft/chronicle/map/impl/CompiledMapIterationContext.java b/src/main/java/net/openhft/chronicle/map/impl/CompiledMapIterationContext.java index ed73a9982..e00138e7b 100644 --- a/src/main/java/net/openhft/chronicle/map/impl/CompiledMapIterationContext.java +++ b/src/main/java/net/openhft/chronicle/map/impl/CompiledMapIterationContext.java @@ -40,7 +40,7 @@ * Generated code */ @SuppressWarnings({"rawtypes", "unchecked", "this-escape"}) -public class CompiledMapIterationContext extends ChainingInterface implements AutoCloseable , ChecksumEntry , HashEntry , HashSegmentContext> , SegmentLock , Alloc , KeyHashCode , LocksInterface , MapContext , MapEntry , IterationContext , VanillaChronicleMapHolder , SetContext { +public class CompiledMapIterationContext extends ChainingInterface implements AutoCloseable, ChecksumEntry, HashEntry, HashSegmentContext>, SegmentLock, Alloc, KeyHashCode, LocksInterface, MapContext, MapEntry, IterationContext, VanillaChronicleMapHolder, SetContext { public boolean readZeroGuarded() { if (!(this.locksInit())) this.initLocks(); @@ -152,7 +152,7 @@ public void doCloseAllocatedChunks() { public void doCloseDelayedUpdateChecksum() { if (!(this.delayedUpdateChecksumInit())) - return ; + return; if (this.h().checksumEntries) this.hashEntryChecksumStrategy.computeAndStoreChecksum(); @@ -202,7 +202,7 @@ public void doCloseKeySize() { public void doCloseLocks() { if (!(this.locksInit())) - return ; + return; if ((rootContextLockedOnThisSegment) == (this)) { closeRootLocks(); @@ -228,7 +228,7 @@ public void doCloseSearchKey() { public void doCloseSegment() { if (!(this.segmentInit())) - return ; + return; entrySpaceOffset = 0; } @@ -247,7 +247,7 @@ public void doCloseSegmentTier() { public void doCloseUsed() { if (!(this.usedInit())) - return ; + return; used = false; if (firstContextLockedInThisThread) @@ -326,7 +326,7 @@ public void setLocalLockStateGuarded(LocalLockState newState) { setLocalLockState(newState); } - public CompiledMapIterationContext(ChainingInterface rootContextInThisThread ,VanillaChronicleMap map) { + public CompiledMapIterationContext(ChainingInterface rootContextInThisThread, VanillaChronicleMap map) { contextChain = rootContextInThisThread.getContextChain(); indexInContextChain = contextChain.size(); contextChain.add(this); @@ -345,7 +345,7 @@ public CompiledMapIterationContext(ChainingInterface rootContextInThisThread ,Va this.segmentBytes = CompiledMapIterationContext.unmonitoredVanillaBytes(segmentBS); this.hashEntryChecksumStrategy = new HashEntryChecksumStrategy(); this.checksumStrategy = this.h().checksumEntries ? this.hashEntryChecksumStrategy : NoChecksumStrategy.INSTANCE; - this.freeList = new ReusableBitSet(new SingleThreadedFlatBitSetFrame(MemoryUnit.LONGS.align(this.h().actualChunksPerSegmentTier, MemoryUnit.BITS)) , Access.nativeAccess() , null , 0); + this.freeList = new ReusableBitSet(new SingleThreadedFlatBitSetFrame(MemoryUnit.LONGS.align(this.h().actualChunksPerSegmentTier, MemoryUnit.BITS)), Access.nativeAccess(), null, 0); this.innerUpdateLock = new UpdateLock(); } @@ -368,7 +368,7 @@ public CompiledMapIterationContext(VanillaChronicleMap map) { this.segmentBytes = CompiledMapIterationContext.unmonitoredVanillaBytes(segmentBS); this.hashEntryChecksumStrategy = new HashEntryChecksumStrategy(); this.checksumStrategy = this.h().checksumEntries ? this.hashEntryChecksumStrategy : NoChecksumStrategy.INSTANCE; - this.freeList = new ReusableBitSet(new SingleThreadedFlatBitSetFrame(MemoryUnit.LONGS.align(this.h().actualChunksPerSegmentTier, MemoryUnit.BITS)) , Access.nativeAccess() , null , 0); + this.freeList = new ReusableBitSet(new SingleThreadedFlatBitSetFrame(MemoryUnit.LONGS.align(this.h().actualChunksPerSegmentTier, MemoryUnit.BITS)), Access.nativeAccess(), null, 0); this.innerUpdateLock = new UpdateLock(); } @@ -470,7 +470,7 @@ public K getUsing(K using) { public class EntryValueBytesData extends AbstractData { public void doCloseCachedEntryValue() { if (!(this.cachedEntryValueInit())) - return ; + return; cachedEntryValueRead = false; } @@ -507,7 +507,7 @@ public V getUsing(V using) { return innerGetUsing(using); } - private V cachedEntryValue = (CompiledMapIterationContext.this.m().valueType()) == (CharSequence.class) ? ((V)(new StringBuilder())) : null; + private V cachedEntryValue = (CompiledMapIterationContext.this.m().valueType()) == (CharSequence.class) ? ((V) (new StringBuilder())) : null; private boolean cachedEntryValueRead = false; @@ -529,7 +529,7 @@ public V cachedEntryValue() { public void closeCachedEntryValue() { if (!(this.cachedEntryValueInit())) - return ; + return; cachedEntryValueRead = false; } @@ -566,7 +566,7 @@ public int computeChecksum() { } else { checksum = keyHashCode; } - return ((int)((checksum >>> 32) ^ checksum)); + return ((int) ((checksum >>> 32) ^ checksum)); } public void closeHashEntryChecksumStrategyComputeChecksumDependants() { @@ -610,10 +610,10 @@ public void lockInterruptibly() throws InterruptedException { } catch (InterProcessDeadLockException e) { throw CompiledMapIterationContext.this.debugContextsAndLocksGuarded(e); } - } + } CompiledMapIterationContext.this.incrementReadGuarded(); CompiledMapIterationContext.this.setLocalLockStateGuarded(LocalLockState.READ_LOCKED); - } + } } @Override @@ -626,10 +626,10 @@ public void lock() { } catch (InterProcessDeadLockException e) { throw CompiledMapIterationContext.this.debugContextsAndLocksGuarded(e); } - } + } CompiledMapIterationContext.this.incrementReadGuarded(); CompiledMapIterationContext.this.setLocalLockStateGuarded(LocalLockState.READ_LOCKED); - } + } } public void closeReadLockLockDependants() { @@ -648,7 +648,7 @@ public void unlock() { if ((CompiledMapIterationContext.this.localLockState()) != (LocalLockState.UNLOCKED)) { CompiledMapIterationContext.this.closeHashLookupPos(); CompiledMapIterationContext.this.closeEntry(); - } + } CompiledMapIterationContext.this.readUnlockAndDecrementCountGuarded(); CompiledMapIterationContext.this.setLocalLockStateGuarded(LocalLockState.UNLOCKED); } @@ -715,7 +715,7 @@ public void lockInterruptibly() throws InterruptedException { throw new InterruptedException(); switch (CompiledMapIterationContext.this.localLockState()) { - case UNLOCKED : + case UNLOCKED: CompiledMapIterationContext.this.checkIterationContextNotLockedInThisThread(); if ((CompiledMapIterationContext.this.updateZeroGuarded()) && (CompiledMapIterationContext.this.writeZeroGuarded())) { if (!(CompiledMapIterationContext.this.readZeroGuarded())) @@ -726,14 +726,14 @@ public void lockInterruptibly() throws InterruptedException { } catch (InterProcessDeadLockException e) { throw CompiledMapIterationContext.this.debugContextsAndLocksGuarded(e); } - } + } CompiledMapIterationContext.this.incrementUpdateGuarded(); CompiledMapIterationContext.this.setLocalLockStateGuarded(LocalLockState.UPDATE_LOCKED); - return ; - case READ_LOCKED : + return; + case READ_LOCKED: throw forbiddenUpgrade(); - case UPDATE_LOCKED : - case WRITE_LOCKED : + case UPDATE_LOCKED: + case WRITE_LOCKED: } } @@ -747,16 +747,16 @@ public boolean isHeldByCurrentThread() { public void unlock() { CompiledMapIterationContext.this.checkOnEachLockOperation(); switch (CompiledMapIterationContext.this.localLockState()) { - case UNLOCKED : - case READ_LOCKED : - return ; - case UPDATE_LOCKED : + case UNLOCKED: + case READ_LOCKED: + return; + case UPDATE_LOCKED: CompiledMapIterationContext.this.closeDelayedUpdateChecksum(); if (((CompiledMapIterationContext.this.decrementUpdateGuarded()) == 0) && (CompiledMapIterationContext.this.writeZeroGuarded())) { CompiledMapIterationContext.this.segmentHeader().downgradeUpdateToReadLock(CompiledMapIterationContext.this.segmentHeaderAddress()); - } + } break; - case WRITE_LOCKED : + case WRITE_LOCKED: CompiledMapIterationContext.this.closeDelayedUpdateChecksum(); if ((CompiledMapIterationContext.this.decrementWriteGuarded()) == 0) { if (!(CompiledMapIterationContext.this.updateZeroGuarded())) { @@ -764,7 +764,7 @@ public void unlock() { } else { CompiledMapIterationContext.this.segmentHeader().downgradeWriteToReadLock(CompiledMapIterationContext.this.segmentHeaderAddress()); } - } + } } CompiledMapIterationContext.this.incrementReadGuarded(); CompiledMapIterationContext.this.setLocalLockStateGuarded(LocalLockState.READ_LOCKED); @@ -774,7 +774,7 @@ public void unlock() { public void lock() { CompiledMapIterationContext.this.checkOnEachLockOperation(); switch (CompiledMapIterationContext.this.localLockState()) { - case UNLOCKED : + case UNLOCKED: CompiledMapIterationContext.this.checkIterationContextNotLockedInThisThread(); if ((CompiledMapIterationContext.this.updateZeroGuarded()) && (CompiledMapIterationContext.this.writeZeroGuarded())) { if (!(CompiledMapIterationContext.this.readZeroGuarded())) @@ -785,14 +785,14 @@ public void lock() { } catch (InterProcessDeadLockException e) { throw CompiledMapIterationContext.this.debugContextsAndLocksGuarded(e); } - } + } CompiledMapIterationContext.this.incrementUpdateGuarded(); CompiledMapIterationContext.this.setLocalLockStateGuarded(LocalLockState.UPDATE_LOCKED); - return ; - case READ_LOCKED : + return; + case READ_LOCKED: throw forbiddenUpgrade(); - case UPDATE_LOCKED : - case WRITE_LOCKED : + case UPDATE_LOCKED: + case WRITE_LOCKED: } } @@ -800,7 +800,7 @@ public void lock() { public boolean tryLock() { CompiledMapIterationContext.this.checkOnEachLockOperation(); switch (CompiledMapIterationContext.this.localLockState()) { - case UNLOCKED : + case UNLOCKED: CompiledMapIterationContext.this.checkIterationContextNotLockedInThisThread(); if ((CompiledMapIterationContext.this.updateZeroGuarded()) && (CompiledMapIterationContext.this.writeZeroGuarded())) { if (!(CompiledMapIterationContext.this.readZeroGuarded())) @@ -818,12 +818,12 @@ public boolean tryLock() { CompiledMapIterationContext.this.setLocalLockStateGuarded(LocalLockState.UPDATE_LOCKED); return true; } - case READ_LOCKED : + case READ_LOCKED: throw forbiddenUpgrade(); - case UPDATE_LOCKED : - case WRITE_LOCKED : + case UPDATE_LOCKED: + case WRITE_LOCKED: return true; - default : + default: throw new IllegalStateException((((CompiledMapIterationContext.this.h().toIdentityString()) + ": unexpected localLockState=") + (CompiledMapIterationContext.this.localLockState()))); } } @@ -836,7 +836,7 @@ public boolean tryLock(long time, @NotNull throw new InterruptedException(); switch (CompiledMapIterationContext.this.localLockState()) { - case UNLOCKED : + case UNLOCKED: CompiledMapIterationContext.this.checkIterationContextNotLockedInThisThread(); if ((CompiledMapIterationContext.this.updateZeroGuarded()) && (CompiledMapIterationContext.this.writeZeroGuarded())) { if (!(CompiledMapIterationContext.this.readZeroGuarded())) @@ -854,12 +854,12 @@ public boolean tryLock(long time, @NotNull CompiledMapIterationContext.this.setLocalLockStateGuarded(LocalLockState.UPDATE_LOCKED); return true; } - case READ_LOCKED : + case READ_LOCKED: throw forbiddenUpgrade(); - case UPDATE_LOCKED : - case WRITE_LOCKED : + case UPDATE_LOCKED: + case WRITE_LOCKED: return true; - default : + default: throw new IllegalStateException((((CompiledMapIterationContext.this.h().toIdentityString()) + ": unexpected localLockState=") + (CompiledMapIterationContext.this.localLockState()))); } } @@ -879,13 +879,13 @@ public void doCloseCachedWrappedValue() { public void doCloseNext() { if (!(this.nextInit())) - return ; + return; } public void doCloseWrappedValueBytes() { if (!(this.wrappedValueBytesInit())) - return ; + return; wrappedValueBytes.bytesStore(BytesStore.empty(), 0, 0); wrappedValueBytesUsed = false; @@ -893,7 +893,7 @@ public void doCloseWrappedValueBytes() { public void doCloseWrappedValueBytesStore() { if (!(this.wrappedValueBytesStoreInit())) - return ; + return; wrappedValueBytesStore = null; if ((next) != null) @@ -935,7 +935,7 @@ public WrappedValueBytesData next() { void closeNext() { if (!(this.nextInit())) - return ; + return; this.closeNextDependants(); } @@ -981,7 +981,7 @@ public long wrappedValueBytesOffset() { void closeWrappedValueBytesStore() { if (!(this.wrappedValueBytesStoreInit())) - return ; + return; this.closeWrappedValueBytesStoreDependants(); wrappedValueBytesStore = null; @@ -1019,7 +1019,7 @@ public VanillaBytes wrappedValueBytes() { void closeWrappedValueBytes() { if (!(this.wrappedValueBytesInit())) - return ; + return; this.closeWrappedValueBytesDependants(); wrappedValueBytes.bytesStore(BytesStore.empty(), 0, 0); @@ -1097,7 +1097,7 @@ public RandomDataInput bytes() { public class WrappedValueInstanceDataHolder { public void doCloseValue() { if (!(this.valueInit())) - return ; + return; value = null; if ((next) != null) @@ -1107,13 +1107,13 @@ public void doCloseValue() { public void doCloseNext() { if (!(this.nextInit())) - return ; + return; } public void doCloseWrappedData() { if (!(this.wrappedDataInit())) - return ; + return; wrappedData = null; wrappedValueDataAccess.uninit(); @@ -1157,7 +1157,7 @@ public WrappedValueInstanceDataHolder next() { void closeNext() { if (!(this.nextInit())) - return ; + return; this.closeNextDependants(); } @@ -1188,7 +1188,7 @@ public V value() { public void closeValue() { if (!(this.valueInit())) - return ; + return; this.closeValueDependants(); value = null; @@ -1220,7 +1220,7 @@ public Data wrappedData() { private void closeWrappedData() { if (!(this.wrappedDataInit())) - return ; + return; wrappedData = null; wrappedValueDataAccess.uninit(); @@ -1242,7 +1242,7 @@ private IllegalStateException forbiddenWriteLockWhenOuterContextReadLocked() { public boolean tryLock() { CompiledMapIterationContext.this.checkOnEachLockOperation(); switch (CompiledMapIterationContext.this.localLockState()) { - case UNLOCKED : + case UNLOCKED: CompiledMapIterationContext.this.checkIterationContextNotLockedInThisThread(); if (CompiledMapIterationContext.this.writeZeroGuarded()) { if (!(CompiledMapIterationContext.this.updateZeroGuarded())) { @@ -1270,9 +1270,9 @@ public boolean tryLock() { CompiledMapIterationContext.this.setLocalLockStateGuarded(LocalLockState.WRITE_LOCKED); return true; } - case READ_LOCKED : + case READ_LOCKED: throw forbiddenUpgrade(); - case UPDATE_LOCKED : + case UPDATE_LOCKED: if (CompiledMapIterationContext.this.writeZeroGuarded()) { assert !(CompiledMapIterationContext.this.updateZeroGuarded()); if (CompiledMapIterationContext.this.segmentHeader().tryUpgradeUpdateToWriteLock(CompiledMapIterationContext.this.segmentHeaderAddress())) { @@ -1289,9 +1289,9 @@ public boolean tryLock() { CompiledMapIterationContext.this.setLocalLockStateGuarded(LocalLockState.WRITE_LOCKED); return true; } - case WRITE_LOCKED : + case WRITE_LOCKED: return true; - default : + default: throw new IllegalStateException((((CompiledMapIterationContext.this.h().toIdentityString()) + ": unexpected localLockState=") + (CompiledMapIterationContext.this.localLockState()))); } } @@ -1304,7 +1304,7 @@ public boolean tryLock(long time, @NotNull throw new InterruptedException(); switch (CompiledMapIterationContext.this.localLockState()) { - case UNLOCKED : + case UNLOCKED: CompiledMapIterationContext.this.checkIterationContextNotLockedInThisThread(); if (CompiledMapIterationContext.this.writeZeroGuarded()) { if (!(CompiledMapIterationContext.this.updateZeroGuarded())) { @@ -1332,9 +1332,9 @@ public boolean tryLock(long time, @NotNull CompiledMapIterationContext.this.setLocalLockStateGuarded(LocalLockState.WRITE_LOCKED); return true; } - case READ_LOCKED : + case READ_LOCKED: throw forbiddenUpgrade(); - case UPDATE_LOCKED : + case UPDATE_LOCKED: if (CompiledMapIterationContext.this.writeZeroGuarded()) { assert !(CompiledMapIterationContext.this.updateZeroGuarded()); if (CompiledMapIterationContext.this.segmentHeader().tryUpgradeUpdateToWriteLock(CompiledMapIterationContext.this.segmentHeaderAddress(), time, unit)) { @@ -1351,9 +1351,9 @@ public boolean tryLock(long time, @NotNull CompiledMapIterationContext.this.setLocalLockStateGuarded(LocalLockState.WRITE_LOCKED); return true; } - case WRITE_LOCKED : + case WRITE_LOCKED: return true; - default : + default: throw new IllegalStateException((((CompiledMapIterationContext.this.h().toIdentityString()) + ": unexpected localLockState=") + (CompiledMapIterationContext.this.localLockState()))); } } @@ -1365,7 +1365,7 @@ public void lockInterruptibly() throws InterruptedException { throw new InterruptedException(); switch (CompiledMapIterationContext.this.localLockState()) { - case UNLOCKED : + case UNLOCKED: CompiledMapIterationContext.this.checkIterationContextNotLockedInThisThread(); if (CompiledMapIterationContext.this.writeZeroGuarded()) { if (!(CompiledMapIterationContext.this.updateZeroGuarded())) { @@ -1380,13 +1380,13 @@ public void lockInterruptibly() throws InterruptedException { throw CompiledMapIterationContext.this.debugContextsAndLocksGuarded(e); } } - } + } CompiledMapIterationContext.this.incrementWriteGuarded(); CompiledMapIterationContext.this.setLocalLockStateGuarded(LocalLockState.WRITE_LOCKED); - return ; - case READ_LOCKED : + return; + case READ_LOCKED: throw forbiddenUpgrade(); - case UPDATE_LOCKED : + case UPDATE_LOCKED: if (CompiledMapIterationContext.this.writeZeroGuarded()) { assert !(CompiledMapIterationContext.this.updateZeroGuarded()); try { @@ -1394,12 +1394,12 @@ public void lockInterruptibly() throws InterruptedException { } catch (InterProcessDeadLockException e) { throw CompiledMapIterationContext.this.debugContextsAndLocksGuarded(e); } - } + } CompiledMapIterationContext.this.decrementUpdateGuarded(); CompiledMapIterationContext.this.incrementWriteGuarded(); CompiledMapIterationContext.this.setLocalLockStateGuarded(LocalLockState.WRITE_LOCKED); break; - case WRITE_LOCKED : + case WRITE_LOCKED: break; } } @@ -1408,11 +1408,11 @@ public void lockInterruptibly() throws InterruptedException { public void unlock() { CompiledMapIterationContext.this.checkOnEachLockOperation(); switch (CompiledMapIterationContext.this.localLockState()) { - case UNLOCKED : - case READ_LOCKED : - case UPDATE_LOCKED : - return ; - case WRITE_LOCKED : + case UNLOCKED: + case READ_LOCKED: + case UPDATE_LOCKED: + return; + case WRITE_LOCKED: CompiledMapIterationContext.this.closeDelayedUpdateChecksum(); if ((CompiledMapIterationContext.this.decrementWriteGuarded()) == 0) CompiledMapIterationContext.this.segmentHeader().downgradeWriteToUpdateLock(CompiledMapIterationContext.this.segmentHeaderAddress()); @@ -1426,7 +1426,7 @@ public void unlock() { public void lock() { CompiledMapIterationContext.this.checkOnEachLockOperation(); switch (CompiledMapIterationContext.this.localLockState()) { - case UNLOCKED : + case UNLOCKED: CompiledMapIterationContext.this.checkIterationContextNotLockedInThisThread(); if (CompiledMapIterationContext.this.writeZeroGuarded()) { if (!(CompiledMapIterationContext.this.updateZeroGuarded())) { @@ -1441,13 +1441,13 @@ public void lock() { throw CompiledMapIterationContext.this.debugContextsAndLocksGuarded(e); } } - } + } CompiledMapIterationContext.this.incrementWriteGuarded(); CompiledMapIterationContext.this.setLocalLockStateGuarded(LocalLockState.WRITE_LOCKED); - return ; - case READ_LOCKED : + return; + case READ_LOCKED: throw forbiddenUpgrade(); - case UPDATE_LOCKED : + case UPDATE_LOCKED: if (CompiledMapIterationContext.this.writeZeroGuarded()) { assert !(CompiledMapIterationContext.this.updateZeroGuarded()); try { @@ -1455,12 +1455,12 @@ public void lock() { } catch (InterProcessDeadLockException e) { throw CompiledMapIterationContext.this.debugContextsAndLocksGuarded(e); } - } + } CompiledMapIterationContext.this.decrementUpdateGuarded(); CompiledMapIterationContext.this.incrementWriteGuarded(); CompiledMapIterationContext.this.setLocalLockStateGuarded(LocalLockState.WRITE_LOCKED); break; - case WRITE_LOCKED : + case WRITE_LOCKED: break; } } @@ -1515,7 +1515,8 @@ public int decrementWrite() { } public enum SearchState { -PRESENT, ABSENT; } + PRESENT, ABSENT; + } private long _HashEntryStages_entryEnd() { return keyEnd(); @@ -1525,7 +1526,7 @@ public long allocReturnCode(int chunks) { VanillaChronicleHash h = this.h(); if (chunks > (h.maxChunksPerEntry)) { throw new IllegalArgumentException(((((((this.h().toIdentityString()) + ": Entry is too large: requires ") + chunks) + " chunks, ") + (h.maxChunksPerEntry)) + " is maximum.")); - } + } long lowestPossiblyFreeChunk = lowestPossiblyFreeChunk(); if ((lowestPossiblyFreeChunk + chunks) > (h.actualChunksPerSegmentTier)) return -1; @@ -1539,13 +1540,13 @@ public long allocReturnCode(int chunks) { if ((ret + chunks) > (h.actualChunksPerSegmentTier)) { assert ret != (BitSetFrame.NOT_FOUND); freeList.clearRange(ret, (ret + chunks)); - } + } return -1; } else { tierEntries(((tierEntries()) + 1)); if ((chunks == 1) || (freeList.isSet(lowestPossiblyFreeChunk))) { lowestPossiblyFreeChunk((ret + chunks)); - } + } return ret; } } @@ -1560,11 +1561,11 @@ private void _HashSegmentIteration_hookAfterEachIteration() { private void _SegmentStages_checkNestedContextsQueryDifferentKeys(LocksInterface innermostContextOnThisSegment) { if ((innermostContextOnThisSegment.getClass()) == (getClass())) { - Data key = ((CompiledMapIterationContext)(innermostContextOnThisSegment)).inputKey(); - if (java.util.Objects.equals(key, ((CompiledMapIterationContext)((Object)(this))).inputKey())) { + Data key = ((CompiledMapIterationContext) (innermostContextOnThisSegment)).inputKey(); + if (java.util.Objects.equals(key, ((CompiledMapIterationContext) ((Object) (this))).inputKey())) { throw new IllegalStateException((((this.h().toIdentityString()) + ": Nested same-thread contexts cannot access the same key ") + key)); - } - } + } + } } private void _SegmentStages_nextTier() { @@ -1619,16 +1620,16 @@ public void incrementWrite() { public void readUnlockAndDecrementCount() { switch (localLockState) { - case UNLOCKED : - return ; - case READ_LOCKED : + case UNLOCKED: + return; + case READ_LOCKED: if ((decrementRead()) == 0) { if ((updateZero()) && (writeZero())) segmentHeader().readUnlock(segmentHeaderAddress()); - } - return ; - case UPDATE_LOCKED : + } + return; + case UPDATE_LOCKED: if ((decrementUpdate()) == 0) { if (writeZero()) { if (readZero()) { @@ -1636,10 +1637,10 @@ public void readUnlockAndDecrementCount() { } else { segmentHeader().downgradeUpdateToReadLock(segmentHeaderAddress()); } - } - } - return ; - case WRITE_LOCKED : + } + } + return; + case WRITE_LOCKED: if ((decrementWrite()) == 0) { if (!(updateZero())) { segmentHeader().downgradeWriteToUpdateLock(segmentHeaderAddress()); @@ -1650,7 +1651,7 @@ public void readUnlockAndDecrementCount() { segmentHeader().writeUnlock(segmentHeaderAddress()); } } - } + } } } @@ -1667,7 +1668,7 @@ public void setLocalLockState(LocalLockState newState) { } else if (goingToLock) { registerIterationContextLockedInThisThread(); - } + } localLockState = newState; } @@ -1709,15 +1710,15 @@ private void closeNestedLocks() { private void closeRootLocks() { verifyInnermostContext(); switch (localLockState) { - case UNLOCKED : - return ; - case READ_LOCKED : + case UNLOCKED: + return; + case READ_LOCKED: segmentHeader().readUnlock(segmentHeaderAddress()); - return ; - case UPDATE_LOCKED : + return; + case UPDATE_LOCKED: segmentHeader().updateUnlock(segmentHeaderAddress()); - return ; - case WRITE_LOCKED : + return; + case WRITE_LOCKED: segmentHeader().writeUnlock(segmentHeaderAddress()); } } @@ -1750,7 +1751,7 @@ private void unlinkFromSegmentContextsChain() { private void verifyInnermostContext() { if ((nextNode) != null) { throw new IllegalStateException(((this.h().toIdentityString()) + ": Attempt to close contexts not structurally")); - } + } } public boolean readZero() { @@ -1801,15 +1802,15 @@ public UpdateLock innerUpdateLock() { public RuntimeException debugContextsAndLocks(InterProcessDeadLockException e) { String message = (this.h().toIdentityString()) + ":\n"; message += "Contexts locked on this segment:\n"; - for (LocksInterface cxt = rootContextLockedOnThisSegment ; cxt != null ; cxt = cxt.nextNode()) { + for (LocksInterface cxt = rootContextLockedOnThisSegment; cxt != null; cxt = cxt.nextNode()) { message += (cxt.debugLocksState()) + "\n"; } message += "Current thread contexts:\n"; - for (int i = 0, size = this.contextChain.size() ; i < size ; i++) { + for (int i = 0, size = this.contextChain.size(); i < size; i++) { LocksInterface cxt = this.contextAtIndexInChain(i); message += (cxt.debugLocksState()) + "\n"; } - throw new InterProcessDeadLockException(message , e); + throw new InterProcessDeadLockException(message, e); } final WrappedValueBytesData wrappedValueBytesData; @@ -1877,13 +1878,13 @@ public List contextChain() { return this.contextChain; } - private static T initUsedAndReturn(VanillaChronicleMap map, ChainingInterface context) { + private static T initUsedAndReturn(VanillaChronicleMap map, ChainingInterface context) { try { context.initUsed(true, map); - return ((T)(context)); + return ((T) (context)); } catch (Throwable throwable) { try { - ((AutoCloseable)(context)).close(); + ((AutoCloseable) (context)).close(); } catch (Throwable t) { throwable.addSuppressed(t); } @@ -1913,15 +1914,15 @@ public void closeMapEntryStagesReadFoundEntryDependants() { private void deregisterIterationContextLockedInThisThread() { if ((this) instanceof IterationContext) { this.rootContextInThisThread.iterationContextLockedInThisThread = false; - } + } } public void closeIterationSegmentStagesDeregisterIterationContextLockedInThisThreadDependants() { this.closeLocks(); } - public T contextAtIndexInChain(int index) { - return ((T)(contextChain.get(index))); + public T contextAtIndexInChain(int index) { + return ((T) (contextChain.get(index))); } public void closeVanillaChronicleMapHolderImplContextAtIndexInChainDependants() { @@ -1938,17 +1939,17 @@ public Object entryForIteration() { } @Override - public T getContext(Class contextClass, BiFunction createChaining, VanillaChronicleMap map) { - for (int i = 0 ; i < (contextChain.size()) ; i++) { + public T getContext(Class contextClass, BiFunction createChaining, VanillaChronicleMap map) { + for (int i = 0; i < (contextChain.size()); i++) { ChainingInterface context = contextChain.get(i); if (((context.getClass()) == contextClass) && (!(context.usedInit()))) { return CompiledMapIterationContext.initUsedAndReturn(map, context); - } + } } int maxNestedContexts = 1 << 10; if ((contextChain.size()) > maxNestedContexts) { throw new IllegalStateException(((((((((map.toIdentityString()) + ": More than ") + maxNestedContexts) + " nested ChronicleHash contexts\n") + "are not supported. Very probable that you simply forgot to close context\n") + "somewhere (recommended to use try-with-resources statement).\n") + "Otherwise this is a bug, please report with this\n") + "stack trace on https://github.com/OpenHFT/Chronicle-Map/issues")); - } + } T context = createChaining.apply(this, map); return CompiledMapIterationContext.initUsedAndReturn(map, context); } @@ -1977,7 +1978,7 @@ public long newEntrySize(Data newValue, long entryStartOffset, long newValueO private void registerIterationContextLockedInThisThread() { if ((this) instanceof IterationContext) { this.rootContextInThisThread.iterationContextLockedInThisThread = true; - } + } } public void closeIterationSegmentStagesRegisterIterationContextLockedInThisThreadDependants() { @@ -2014,7 +2015,7 @@ public long keySize() { public void closeKeySize() { if (!(this.keySizeInit())) - return ; + return; this.closeKeySizeDependants(); this.keySize = -1; @@ -2068,7 +2069,7 @@ public int segmentIndex() { public void closeSegmentIndex() { if (!(this.segmentIndexInit())) - return ; + return; this.closeSegmentIndexDependants(); this.segmentIndex = -1; @@ -2114,7 +2115,7 @@ public Data inputKey() { public void closeInputKey() { if (!(this.inputKeyInit())) - return ; + return; this.closeInputKeyDependants(); this.inputKey = null; @@ -2146,7 +2147,7 @@ public long pos() { public void closePos() { if (!(this.posInit())) - return ; + return; this.closePosDependants(); this.pos = -1; @@ -2177,7 +2178,7 @@ public long keyOffset() { public void closeKeyOffset() { if (!(this.keyOffsetInit())) - return ; + return; this.closeKeyOffsetDependants(); this.keyOffset = -1; @@ -2231,7 +2232,7 @@ public long valueSizeOffset() { public void closeValueSizeOffset() { if (!(this.valueSizeOffsetInit())) - return ; + return; this.closeValueSizeOffsetDependants(); this.valueSizeOffset = -1; @@ -2281,7 +2282,7 @@ public VanillaChronicleMap m() { public void closeMap() { if (!(this.mapInit())) - return ; + return; this.closeMapDependants(); this.m = null; @@ -2361,7 +2362,7 @@ public void closeIterationSegmentStagesCheckNestedContextsQueryDifferentKeysDepe public void checkIterationContextNotLockedInThisThread() { if (this.rootContextInThisThread.iterationContextLockedInThisThread) { throw new IllegalStateException((((this.h().toIdentityString()) + ": Update or Write ") + "locking is forbidden in the context of locked iteration context")); - } + } } public CompactOffHeapLinearHashTable hl() { @@ -2403,7 +2404,7 @@ public long searchStartPos() { public void closeSearchKey() { if (!(this.searchKeyInit())) - return ; + return; this.closeSearchKeyDependants(); this.searchKey = CompactOffHeapLinearHashTable.UNSET_KEY; @@ -2447,7 +2448,7 @@ public SegmentHeader segmentHeader() { public void closeSegmentHeader() { if (!(this.segmentHeaderInit())) - return ; + return; this.closeSegmentHeaderDependants(); this.segmentHeader = null; @@ -2467,7 +2468,7 @@ private void resetSegmentLock(ChronicleHashCorruption.Listener corruptionListene if (lockState != (this.segmentHeader().resetLockState())) { ChronicleHashCorruptionImpl.report(corruptionListener, corruption, this.segmentIndex(), () -> ChronicleHashCorruptionImpl.format("lock of segment {} is not clear: {}", this.segmentIndex(), this.segmentHeader().lockStateToString(lockState))); this.segmentHeader().resetLock(this.segmentHeaderAddress()); - } + } } public int tier = -1; @@ -2544,7 +2545,7 @@ public long tierIndex() { public void closeSegmentTier() { if (!(this.segmentTierInit())) - return ; + return; this.closeSegmentTierDependants(); this.tier = -1; @@ -2581,15 +2582,15 @@ private void shiftHashLookupEntries() { if ((hl.remove(hlAddr, hlPos)) != hlPos) { hlPos = hl.stepBack(hlPos); steps--; - } + } break; - } + } hlHolePos = hl.step(hlHolePos); } - } + } hlPos = hl.step(hlPos); steps++; - } while ((hlPos != 0) || (steps == 0) ); + } while ((hlPos != 0) || (steps == 0)); } long keyHash = 0; @@ -2617,7 +2618,7 @@ public long keyHash() { public void closeKeyHash() { if (!(this.keyHashInit())) - return ; + return; this.closeKeyHashDependants(); this.keyHash = 0; @@ -2654,7 +2655,7 @@ public long prevTierIndex() { public void prevTier() { if ((tier()) == 0) { throw new IllegalStateException(((this.h().toIdentityString()) + ": first tier doesn\'t have previous")); - } + } initSegmentTier(((tier()) - 1), prevTierIndex()); } @@ -2693,16 +2694,16 @@ private void zeroOutFirstSegmentTierCountersArea(ChronicleHashCorruption.Listene if ((this.prevTierIndex()) != 0) { ChronicleHashCorruptionImpl.report(corruptionListener, corruption, this.segmentIndex(), () -> ChronicleHashCorruptionImpl.format("stored prev tier index in first tier of segment {}: {}, should be 0", this.segmentIndex(), this.prevTierIndex())); this.prevTierIndex(0); - } + } long tierCountersAreaAddr = this.tierCountersAreaAddr(); if ((TierCountersArea.segmentIndex(tierCountersAreaAddr)) != 0) { ChronicleHashCorruptionImpl.report(corruptionListener, corruption, this.segmentIndex(), () -> ChronicleHashCorruptionImpl.format("stored segment index in first tier of segment {}: {}, should be 0", this.segmentIndex(), TierCountersArea.segmentIndex(tierCountersAreaAddr))); TierCountersArea.segmentIndex(tierCountersAreaAddr, 0); - } + } if ((TierCountersArea.tier(tierCountersAreaAddr)) != 0) { ChronicleHashCorruptionImpl.report(corruptionListener, corruption, this.segmentIndex(), () -> ChronicleHashCorruptionImpl.format("stored tier in first tier of segment {}: {}, should be 0", this.segmentIndex(), TierCountersArea.tier(tierCountersAreaAddr))); TierCountersArea.tier(tierCountersAreaAddr, 0); - } + } } public long tierEntries() { @@ -2750,7 +2751,7 @@ private void recoverTierEntriesCounter(long entries, ChronicleHashCorruption.Lis if ((this.tierEntries()) != entries) { ChronicleHashCorruptionImpl.report(corruptionListener, corruption, this.segmentIndex(), () -> ChronicleHashCorruptionImpl.format((("Wrong number of entries counter for tier with index {}, " + "stored: {}, should be: ") + (this.tierIndex())), this.tierEntries(), entries)); this.tierEntries(entries); - } + } } private long addr() { @@ -2831,7 +2832,7 @@ public PointerBytesStore segmentBS() { void closeSegment() { if (!(this.segmentInit())) - return ; + return; this.closeSegmentDependants(); entrySpaceOffset = 0; @@ -2901,7 +2902,7 @@ public long valueSize() { public void closeValueSize() { if (!(this.valueSizeInit())) - return ; + return; this.closeValueSizeDependants(); this.valueSize = -1; @@ -2972,7 +2973,7 @@ public long keySizeOffset() { public void closeEntryOffset() { if (!(this.entryOffsetInit())) - return ; + return; this.closeEntryOffsetDependants(); this.keySizeOffset = -1; @@ -3061,7 +3062,7 @@ private void recoverLowestPossibleFreeChunkTiered(ChronicleHashCorruption.Listen long finalLowestFreeChunk = lowestFreeChunk; ChronicleHashCorruptionImpl.report(corruptionListener, corruption, this.segmentIndex(), () -> ChronicleHashCorruptionImpl.format(("wrong lowest free chunk for tier with index {}, " + "stored: {}, should be: {}"), this.tierIndex(), this.lowestPossiblyFreeChunk(), finalLowestFreeChunk)); this.lowestPossiblyFreeChunk(lowestFreeChunk); - } + } } public void nextTier() { @@ -3122,13 +3123,13 @@ public void verifyTierCountersAreaData() { int tierSegmentIndex = TierCountersArea.segmentIndex(tierCountersAreaAddr()); if (tierSegmentIndex != (segmentIndex())) { throw new AssertionError(((((((((("segmentIndex: " + (segmentIndex())) + ", tier: ") + (tier())) + ", tierIndex: ") + (tierIndex())) + ", tierBaseAddr: ") + (tierBaseAddr())) + " reports it belongs to segmentIndex ") + tierSegmentIndex)); - } + } if (hasNextTier()) { long currentTierIndex = this.tierIndex(); nextTier(); if ((prevTierIndex()) != currentTierIndex) { throw new AssertionError(((((((((((("segmentIndex: " + (segmentIndex())) + ", tier: ") + (tier())) + ", tierIndex: ") + (tierIndex())) + ", tierBaseAddr: ") + (tierBaseAddr())) + " reports the previous tierIndex is ") + (prevTierIndex())) + " while actually it is ") + currentTierIndex)); - } + } } else { break; } @@ -3138,7 +3139,7 @@ public void verifyTierCountersAreaData() { public void checkAccessingFromOwnerThread() { if ((owner) != (Thread.currentThread())) { throw new ConcurrentModificationException(((this.h().toIdentityString()) + ": Context shouldn\'t be accessed from multiple threads")); - } + } } public void closeOwnerThreadHolderCheckAccessingFromOwnerThreadDependants() { @@ -3158,7 +3159,7 @@ public void checkEntryNotRemovedOnThisIteration() { throwExceptionIfClosed(); if (entryRemovedOnThisIterationInit()) { throw new IllegalStateException(((this.h().toIdentityString()) + ": Entry was already removed on this iteration")); - } + } } public void closeMapSegmentIterationCheckEntryNotRemovedOnThisIterationDependants() { @@ -3177,7 +3178,7 @@ public void closeIterationCheckOnEachPublicOperationCheckOnEachPublicOperationDe @Override public R replaceValue(@NotNull - MapEntry entry, Data newValue) { + MapEntry entry, Data newValue) { this.checkOnEachPublicOperation(); return this.m().entryOperations.replaceValue(entry, newValue); } @@ -3200,7 +3201,7 @@ public Data wrapValueAsData(V value) { @Override public Data defaultValue(@NotNull - MapAbsentEntry absentEntry) { + MapAbsentEntry absentEntry) { this.checkOnEachPublicOperation(); return this.m().defaultValueProvider.defaultValue(absentEntry); } @@ -3224,7 +3225,7 @@ public Data wrapValueBytesAsData(BytesStore bytesStore, long offset, lo @Override public R remove(@NotNull - MapEntry entry) { + MapEntry entry) { this.checkOnEachPublicOperation(); return this.m().entryOperations.remove(entry); } @@ -3241,7 +3242,7 @@ private int checkEntry(long searchKey, long entryPos, int segmentIndex, Chronicl if ((entryPos < 0) || (entryPos >= (h.actualChunksPerSegmentTier))) { ChronicleHashCorruptionImpl.report(corruptionListener, corruption, segmentIndex, () -> ChronicleHashCorruptionImpl.format("Entry pos is out of range: {}, should be 0-{}", entryPos, ((h.actualChunksPerSegmentTier) - 1))); return -1; - } + } try { this.readExistingEntry(entryPos); } catch (Exception e) { @@ -3251,25 +3252,25 @@ private int checkEntry(long searchKey, long entryPos, int segmentIndex, Chronicl if ((this.keyEnd()) > (this.segmentBytes().capacity())) { ChronicleHashCorruptionImpl.report(corruptionListener, corruption, segmentIndex, () -> ChronicleHashCorruptionImpl.format(("Wrong key size: " + (this.keySize())))); return -1; - } + } long keyHashCode = this.keyHashCode(); int segmentIndexFromKey = h.hashSplitting.segmentIndex(keyHashCode); if ((segmentIndexFromKey < 0) || (segmentIndexFromKey >= (h.actualSegments))) { ChronicleHashCorruptionImpl.report(corruptionListener, corruption, segmentIndex, () -> ChronicleHashCorruptionImpl.format(("Segment index from the entry key hash code is out of range: {}, " + "should be 0-{}, entry key: {}"), segmentIndexFromKey, ((h.actualSegments) - 1), this.key())); return -1; - } + } long segmentHashFromKey = h.hashSplitting.segmentHash(keyHashCode); long searchKeyFromKey = h.hashLookup.maskUnsetKey(segmentHashFromKey); if (searchKey != searchKeyFromKey) { ChronicleHashCorruptionImpl.report(corruptionListener, corruption, segmentIndex, () -> ChronicleHashCorruptionImpl.format(("HashLookup searchKey: {}, HashLookup searchKey " + "from the entry key hash code: {}, entry key: {}, entry pos: {}"), searchKey, searchKeyFromKey, this.key(), entryPos)); return -1; - } + } try { long entryAndChecksumEnd = (this.entryEnd()) + (this.checksumStrategy.extraEntryBytes()); if (entryAndChecksumEnd > (this.segmentBytes().capacity())) { ChronicleHashCorruptionImpl.report(corruptionListener, corruption, segmentIndex, () -> ChronicleHashCorruptionImpl.format(("Wrong value size: {}, key: " + (this.valueSize())), this.key())); return -1; - } + } } catch (Exception ex) { ChronicleHashCorruptionImpl.reportException(corruptionListener, corruption, segmentIndex, () -> "Exception while reading entry value size, key: " + (this.key()), ex); return -1; @@ -3279,11 +3280,11 @@ private int checkEntry(long searchKey, long entryPos, int segmentIndex, Chronicl if (storedChecksum != checksumFromEntry) { ChronicleHashCorruptionImpl.report(corruptionListener, corruption, segmentIndex, () -> ChronicleHashCorruptionImpl.format(("Checksum doesn\'t match, stored: {}, should be from " + "the entry bytes: {}, key: {}, value: {}"), storedChecksum, checksumFromEntry, this.key(), this.value())); return -1; - } + } if (!(this.freeList().isRangeClear(entryPos, (entryPos + (this.entrySizeInChunks()))))) { ChronicleHashCorruptionImpl.report(corruptionListener, corruption, segmentIndex, () -> ChronicleHashCorruptionImpl.format("Overlapping entry: positions {}-{}, key: {}, value: {}", entryPos, ((entryPos + (this.entrySizeInChunks())) - 1), this.key(), this.value())); return -1; - } + } if (segmentIndex < 0) { return segmentIndexFromKey; } else { @@ -3307,7 +3308,8 @@ public void removeDuplicatesInSegment(ChronicleHashCorruption.Listener corruptio long hlPos = startHlPos; int steps = 0; long entries = 0; - tierIteration : do { + tierIteration: + do { hlPos = hashLookup.step(hlPos); steps++; long entry = hashLookup.readEntry(currentTierBaseAddr, hlPos); @@ -3316,28 +3318,28 @@ public void removeDuplicatesInSegment(ChronicleHashCorruption.Listener corruptio Data key = this.key(); try (ExternalMapQueryContext c = m.queryContext(key)) { MapEntry entry2 = c.entry(); - Data key2 = ((MapEntry)(c)).key(); + Data key2 = ((MapEntry) (c)).key(); long keyAddress = key.bytes().addressForRead(key.offset()); long key2Address = key2.bytes().addressForRead(key2.offset()); if (key2Address != keyAddress) { - ChronicleHashCorruptionImpl.report(corruptionListener, corruption, this.segmentIndex(), () -> ChronicleHashCorruptionImpl.format(("entries with duplicate key {} in segment {}: " + "with values {} and {}, removing the latter"), key, c.segmentIndex(), (entry2 != null ? ((MapEntry)(c)).value() : ""), (!(this.entryDeleted()) ? this.value() : ""))); + ChronicleHashCorruptionImpl.report(corruptionListener, corruption, this.segmentIndex(), () -> ChronicleHashCorruptionImpl.format(("entries with duplicate key {} in segment {}: " + "with values {} and {}, removing the latter"), key, c.segmentIndex(), (entry2 != null ? ((MapEntry) (c)).value() : ""), (!(this.entryDeleted()) ? this.value() : ""))); if ((hashLookup.remove(currentTierBaseAddr, hlPos)) != hlPos) { hlPos = hashLookup.stepBack(hlPos); steps--; - } + } continue tierIteration; - } + } } entries++; - } - } while ((hlPos != startHlPos) || (steps == 0) ); + } + } while ((hlPos != startHlPos) || (steps == 0)); recoverTierEntriesCounter(entries, corruptionListener, corruption); recoverLowestPossibleFreeChunkTiered(corruptionListener, corruption); } private void removeDuplicatesInSegments(ChronicleHashCorruption.Listener corruptionListener, ChronicleHashCorruptionImpl corruption) { VanillaChronicleHash h = this.h(); - for (int segmentIndex = 0 ; segmentIndex < (h.actualSegments) ; segmentIndex++) { + for (int segmentIndex = 0; segmentIndex < (h.actualSegments); segmentIndex++) { this.initSegmentIndex(segmentIndex); this.initSegmentTier(); this.goToLastTier(); @@ -3361,12 +3363,13 @@ public int recoverTier(int segmentIndex, ChronicleHashCorruption.Listener corrup long hlPos = 0; do { long hlEntry = hl.readEntry(hlAddr, hlPos); - nextHlPos : if (!(hl.empty(hlEntry))) { + nextHlPos: + if (!(hl.empty(hlEntry))) { hl.clearEntry(hlAddr, hlPos); if (validEntries >= (h.maxEntriesPerHashLookup)) { ChronicleHashCorruptionImpl.report(corruptionListener, corruption, segmentIndex, () -> ChronicleHashCorruptionImpl.format("Too many entries in tier with index {}, max is {}", this.tierIndex(), h.maxEntriesPerHashLookup)); break nextHlPos; - } + } long searchKey = hl.key(hlEntry); long entryPos = hl.value(hlEntry); int si = checkEntry(searchKey, entryPos, segmentIndex, corruptionListener, corruption); @@ -3384,16 +3387,17 @@ public int recoverTier(int segmentIndex, ChronicleHashCorruption.Listener corrup hl.writeEntry(hlAddr, insertPos, hl.entry(searchKey, entryPos)); validEntries++; break nextHlPos; - } + } if (insertPos == hlPos) { throw new ChronicleHashRecoveryFailedException((("Concurrent modification of " + (h.toIdentityString())) + " while recovery procedure is in progress")); - } - checkDuplicateKeys : if ((hl.key(hlInsertEntry)) == searchKey) { + } + checkDuplicateKeys: + if ((hl.key(hlInsertEntry)) == searchKey) { long anotherEntryPos = hl.value(hlInsertEntry); if (anotherEntryPos == entryPos) { validEntries++; break nextHlPos; - } + } long currentKeyOffset = this.keyOffset(); long currentKeySize = this.keySize(); int currentEntrySizeInChunks = this.entrySizeInChunks(); @@ -3401,19 +3405,19 @@ public int recoverTier(int segmentIndex, ChronicleHashCorruption.Listener corrup this.readExistingEntry(anotherEntryPos); } else if ((checkEntry(searchKey, anotherEntryPos, segmentIndex, corruptionListener, corruption)) < 0) { break checkDuplicateKeys; - } + } if (((this.keySize()) == currentKeySize) && (BytesUtil.bytesEqual(this.segmentBS(), currentKeyOffset, this.segmentBS(), this.keyOffset(), currentKeySize))) { ChronicleHashCorruptionImpl.report(corruptionListener, corruption, segmentIndex, () -> ChronicleHashCorruptionImpl.format(("Entries with duplicate keys within a tier: " + "at pos {} and {} with key {}, first value is {}"), entryPos, anotherEntryPos, this.key(), this.value())); this.freeList().clearRange(entryPos, (entryPos + currentEntrySizeInChunks)); break nextHlPos; - } - } + } + } insertPos = hl.step(insertPos); - } while (insertPos != startInsertPos ); + } while (insertPos != startInsertPos); throw new ChronicleHashRecoveryFailedException(((("HashLookup overflow should never occur. " + "It might also be concurrent access to ") + (h.toIdentityString())) + " while recovery procedure is in progress")); - } + } hlPos = hl.step(hlPos); - } while (hlPos != 0 ); + } while (hlPos != 0); shiftHashLookupEntries(); return segmentIndex; } @@ -3422,7 +3426,7 @@ public int recoverTier(int segmentIndex, ChronicleHashCorruption.Listener corrup public void recoverSegments(ChronicleHashCorruption.Listener corruptionListener, ChronicleHashCorruptionImpl corruption) { throwExceptionIfClosed(); VanillaChronicleHash h = this.h(); - for (int segmentIndex = 0 ; segmentIndex < (h.actualSegments) ; segmentIndex++) { + for (int segmentIndex = 0; segmentIndex < (h.actualSegments); segmentIndex++) { this.initSegmentIndex(segmentIndex); resetSegmentLock(corruptionListener, corruption); zeroOutFirstSegmentTierCountersArea(corruptionListener, corruption); @@ -3434,7 +3438,7 @@ public void recoverSegments(ChronicleHashCorruption.Listener corruptionListener, long expectedExtraTiersInUse = Math.max(0, Math.min(storedExtraTiersInUse, allocatedExtraTiers)); long actualExtraTiersInUse = 0; long firstFreeExtraTierIndex = -1; - for (long extraTierIndex = 0 ; extraTierIndex < expectedExtraTiersInUse ; extraTierIndex++) { + for (long extraTierIndex = 0; extraTierIndex < expectedExtraTiersInUse; extraTierIndex++) { long tierIndex = h.extraTierIndexToTierIndex(extraTierIndex); this.initSegmentTier(0, tierIndex); int segmentIndex = this.recoverTier(-1, corruptionListener, corruption); @@ -3444,7 +3448,7 @@ public void recoverSegments(ChronicleHashCorruption.Listener corruptionListener, if (storedSegmentIndex != segmentIndex) { ChronicleHashCorruptionImpl.report(corruptionListener, corruption, segmentIndex, () -> ChronicleHashCorruptionImpl.format(("wrong segment index stored in tier counters area " + "of tier with index {}: {}, should be, based on entries: {}"), tierIndex, storedSegmentIndex, segmentIndex)); TierCountersArea.segmentIndex(tierCountersAreaAddr, segmentIndex); - } + } TierCountersArea.nextTierIndex(tierCountersAreaAddr, 0); this.initSegmentIndex(segmentIndex); this.goToLastTier(); @@ -3461,7 +3465,7 @@ public void recoverSegments(ChronicleHashCorruption.Listener corruptionListener, long finalActualExtraTiersInUse = actualExtraTiersInUse; ChronicleHashCorruptionImpl.report(corruptionListener, corruption, -1, () -> ChronicleHashCorruptionImpl.format((("wrong number of actual tiers in use in global mutable state, stored: {}, " + "should be: ") + storedExtraTiersInUse), finalActualExtraTiersInUse)); globalMutableState.setExtraTiersInUse(actualExtraTiersInUse); - } + } long firstFreeTierIndex; if (firstFreeExtraTierIndex == (-1)) { if (allocatedExtraTiers > expectedExtraTiersInUse) { @@ -3475,12 +3479,12 @@ public void recoverSegments(ChronicleHashCorruption.Listener corruptionListener, if (firstFreeTierIndex > 0) { long lastTierIndex = h.extraTierIndexToTierIndex((allocatedExtraTiers - 1)); h.linkAndZeroOutFreeTiers(firstFreeTierIndex, lastTierIndex); - } + } long storedFirstFreeTierIndex = globalMutableState.getFirstFreeTierIndex(); if (storedFirstFreeTierIndex != firstFreeTierIndex) { ChronicleHashCorruptionImpl.report(corruptionListener, corruption, -1, () -> ChronicleHashCorruptionImpl.format((("wrong first free tier index in global mutable state, stored: {}, " + "should be: ") + storedFirstFreeTierIndex), firstFreeTierIndex)); globalMutableState.setFirstFreeTierIndex(firstFreeTierIndex); - } + } removeDuplicatesInSegments(corruptionListener, corruption); } @@ -3500,7 +3504,7 @@ public InterProcessLock updateLock() { @Override public R insert(@NotNull - MapAbsentEntry absentEntry, Data value) { + MapAbsentEntry absentEntry, Data value) { this.checkOnEachPublicOperation(); return this.m().entryOperations.insert(absentEntry, value); } @@ -3534,7 +3538,7 @@ public boolean used() { @SuppressWarnings(value = "unused") void closeUsed() { if (!(this.usedInit())) - return ; + return; this.closeUsedDependants(); used = false; @@ -3577,14 +3581,14 @@ void initLocks() { localLockState = LocalLockState.UNLOCKED; int indexOfThisContext = this.indexInContextChain; - for (int i = indexOfThisContext - 1 ; i >= 0 ; i--) { + for (int i = indexOfThisContext - 1; i >= 0; i--) { if (tryFindInitLocksOfThisSegment(i)) - return ; + return; } - for (int i = indexOfThisContext + 1, size = this.contextChain.size() ; i < size ; i++) { + for (int i = indexOfThisContext + 1, size = this.contextChain.size(); i < size; i++) { if (tryFindInitLocksOfThisSegment(i)) - return ; + return; } rootContextLockedOnThisSegment = this; @@ -3650,7 +3654,7 @@ public LocksInterface rootContextLockedOnThisSegment() { void closeLocks() { if (!(this.locksInit())) - return ; + return; this.closeLocksDependants(); if ((rootContextLockedOnThisSegment) == (this)) { @@ -3703,7 +3707,7 @@ public long hashLookupPos() { public void closeHashLookupPos() { if (!(this.hashLookupPosInit())) - return ; + return; this.closeHashLookupPosDependants(); this.hashLookupPos = -1; @@ -3722,7 +3726,7 @@ public long nextPos() { if (hl.empty(entry)) { this.setHashLookupPosGuarded(pos); return -1L; - } + } pos = hl.step(pos); if (pos == (searchStartPos())) break; @@ -3730,7 +3734,7 @@ public long nextPos() { if ((hl.key(entry)) == (searchKey())) { this.setHashLookupPosGuarded(pos); return hl.value(entry); - } + } } throw new IllegalStateException(((this.h().toIdentityString()) + ": HashLookup overflow should never occur")); } @@ -3754,7 +3758,7 @@ public boolean keySearchInit() { } public void initKeySearch() { - for (long pos ; (pos = this.nextPos()) >= 0L ; ) { + for (long pos; (pos = this.nextPos()) >= 0L; ) { if (inputKeyInit()) { long keySizeOffset = (this.entrySpaceOffset()) + (pos * (this.m().chunkSize)); Bytes segmentBytes = this.segmentBytesForReadGuarded(); @@ -3767,8 +3771,8 @@ public void initKeySearch() { this.found(); this.readFoundEntry(pos, keySizeOffset, keySize, keyOffset); searchState = CompiledMapIterationContext.SearchState.PRESENT; - return ; - } + return; + } } searchState = CompiledMapIterationContext.SearchState.ABSENT; } @@ -3799,7 +3803,7 @@ public void putNewVolatile(long entryPos) { if (keySearchReInit) { this.readExistingEntry(entryPos); - } + } hl().checkValueForPut(entryPos); hl().writeEntryVolatile(addr(), this.hashLookupPos(), searchKey(), entryPos); } @@ -3819,17 +3823,17 @@ public String debugLocksState() { if (!(this.usedInit())) { s += "unused"; return s; - } + } s += "used, "; if (!(segmentIndexInit())) { s += "segment uninitialized"; return s; - } + } s += ("segment " + (segmentIndex())) + ", "; if (!(locksInit())) { s += "locks uninitialized"; return s; - } + } s += ("local state: " + (localLockState())) + ", "; s += ("read lock count: " + (rootContextLockedOnThisSegment().totalReadLockCount())) + ", "; s += ("update lock count: " + (rootContextLockedOnThisSegment().totalUpdateLockCount())) + ", "; @@ -3842,7 +3846,7 @@ public boolean checkSum() { this.checkOnEachPublicOperation(); if (!(this.h().checksumEntries)) { throw new UnsupportedOperationException(((this.h().toIdentityString()) + ": Checksum is not stored in this Chronicle Hash")); - } + } this.innerUpdateLock.lock(); return (delayedUpdateChecksumInit()) || (checksumStrategy.innerCheckSum()); } @@ -3852,12 +3856,12 @@ public void updateChecksum() { this.checkOnEachPublicOperation(); if (!(this.h().checksumEntries)) { throw new UnsupportedOperationException(((this.h().toIdentityString()) + ": Checksum is not stored in this Chronicle Hash")); - } + } this.innerUpdateLock.lock(); initDelayedUpdateChecksum(true); } - public boolean forEachTierEntryWhile(Predicate predicate, int currentTier, long currentTierBaseAddr, long tierIndex) { + public boolean forEachTierEntryWhile(Predicate predicate, int currentTier, long currentTierBaseAddr, long tierIndex) { long leftEntries = tierEntriesForIteration(); boolean interrupted = false; long startPos = 0L; @@ -3879,7 +3883,7 @@ public boolean forEachTierEntryWhile(Predicate predicate, int curr if (shouldTestEntry()) { initEntryRemovedOnThisIteration(false); try { - if (!(predicate.test(((T)(entryForIteration()))))) { + if (!(predicate.test(((T) (entryForIteration()))))) { interrupted = true; break; } else { @@ -3894,20 +3898,20 @@ public boolean forEachTierEntryWhile(Predicate predicate, int curr currentHashLookupPos = hashLookup.stepBack(currentHashLookupPos); steps--; this.initHashLookupPos(currentHashLookupPos); - } + } this.innerWriteLock.unlock(); this.closeKeyOffset(); } - } - } - } while ((currentHashLookupPos != startPos) || (steps == 0) ); + } + } + } while ((currentHashLookupPos != startPos) || (steps == 0)); if ((!interrupted) && (leftEntries > 0)) { throw new IllegalStateException((((((this.h().toIdentityString()) + ": We went through a tier without interruption, ") + "but according to tier counters there should be ") + leftEntries) + " more entries. Size diverged?")); - } + } return interrupted; } - public boolean innerForEachSegmentEntryWhile(Predicate predicate) { + public boolean innerForEachSegmentEntryWhile(Predicate predicate) { try { this.goToLastTier(); while (true) { @@ -3955,7 +3959,7 @@ protected void relocation(Data newValue, long newEntrySize) { if (!(this.searchStateAbsent())) throw new AssertionError(); - } + } initValue(newValue); freeExtraAllocatedChunks(); CompactOffHeapLinearHashTable hl = this.h().hashLookup; @@ -3978,18 +3982,19 @@ public void innerDefaultReplaceValue(Data newValue) { long newValueOffset = VanillaChronicleMap.alignAddr((entryStartOffset + newSizeOfEverythingBeforeValue), this.m().alignment); long newEntrySize = newEntrySize(newValue, entryStartOffset, newValueOffset); int newSizeInChunks = m.inChunks(newEntrySize); - newValueDoesNotFit : if (newSizeInChunks > (entrySizeInChunks())) { + newValueDoesNotFit: + if (newSizeInChunks > (entrySizeInChunks())) { if (newSizeInChunks > (m.maxChunksPerEntry)) { throw new IllegalArgumentException(((((((m.toIdentityString()) + ": Value too large: entry takes ") + newSizeInChunks) + " chunks, ") + (m.maxChunksPerEntry)) + " is maximum.")); - } + } if (this.reallocGuarded(pos(), entrySizeInChunks(), newSizeInChunks)) { break newValueDoesNotFit; - } + } relocation(newValue, newEntrySize); - return ; + return; } else if (newSizeInChunks < (entrySizeInChunks())) { this.freeExtraGuarded(pos(), entrySizeInChunks(), newSizeInChunks); - } + } } this.innerWriteLock.lock(); if (newValueSizeIsDifferent) { @@ -4019,7 +4024,7 @@ public void iterationRemove() { throwExceptionIfClosed(); if ((this.h().hashLookup.remove(this.tierBaseAddr(), this.hashLookupPos())) != (this.hashLookupPos())) { this.setHashLookupPosGuarded(this.h().hashLookup.stepBack(this.hashLookupPos())); - } + } this.innerRemoveEntryExceptHashLookupUpdate(); } @@ -4051,7 +4056,7 @@ public void initDelayedUpdateChecksum(boolean delayedUpdateChecksum) { public void closeDelayedUpdateChecksum() { if (!(this.delayedUpdateChecksumInit())) - return ; + return; if (this.h().checksumEntries) this.hashEntryChecksumStrategy.computeAndStoreChecksum(); diff --git a/src/main/java/net/openhft/chronicle/map/impl/CompiledMapQueryContext.java b/src/main/java/net/openhft/chronicle/map/impl/CompiledMapQueryContext.java index 1a6427a20..dcbd4e2ea 100644 --- a/src/main/java/net/openhft/chronicle/map/impl/CompiledMapQueryContext.java +++ b/src/main/java/net/openhft/chronicle/map/impl/CompiledMapQueryContext.java @@ -1788,10 +1788,12 @@ public int decrementWrite() { } public enum EntryPresence { -PRESENT, ABSENT; } + PRESENT, ABSENT; + } public enum SearchState { -PRESENT, ABSENT; } + PRESENT, ABSENT; + } private long _HashEntryStages_entryEnd() { return keyEnd(); diff --git a/src/main/java/net/openhft/chronicle/map/impl/CompiledReplicatedMapIterationContext.java b/src/main/java/net/openhft/chronicle/map/impl/CompiledReplicatedMapIterationContext.java index a635a73a5..e090ba4e6 100644 --- a/src/main/java/net/openhft/chronicle/map/impl/CompiledReplicatedMapIterationContext.java +++ b/src/main/java/net/openhft/chronicle/map/impl/CompiledReplicatedMapIterationContext.java @@ -344,7 +344,8 @@ public void setLocalLockStateGuarded(LocalLockState newState) { } enum EntriesToTest { -PRESENT, ALL; } + PRESENT, ALL; + } private long _MapEntryStages_countValueSizeOffset() { return keyEnd(); @@ -1671,7 +1672,8 @@ public int decrementWrite() { } public enum SearchState { -PRESENT, ABSENT; } + PRESENT, ABSENT; + } private long _HashEntryStages_entryEnd() { return keyEnd(); diff --git a/src/main/java/net/openhft/chronicle/map/impl/CompiledReplicatedMapQueryContext.java b/src/main/java/net/openhft/chronicle/map/impl/CompiledReplicatedMapQueryContext.java index efb636a17..7e117c6d3 100644 --- a/src/main/java/net/openhft/chronicle/map/impl/CompiledReplicatedMapQueryContext.java +++ b/src/main/java/net/openhft/chronicle/map/impl/CompiledReplicatedMapQueryContext.java @@ -1848,10 +1848,12 @@ public int decrementWrite() { } public enum EntryPresence { -PRESENT, ABSENT; } + PRESENT, ABSENT; + } public enum SearchState { -PRESENT, ABSENT; } + PRESENT, ABSENT; + } private long _HashEntryStages_entryEnd() { return keyEnd(); diff --git a/src/main/java/net/openhft/chronicle/map/impl/stage/data/bytes/WrappedValueBytesData.java b/src/main/java/net/openhft/chronicle/map/impl/stage/data/bytes/WrappedValueBytesData.java index 7665aead4..af316c51a 100644 --- a/src/main/java/net/openhft/chronicle/map/impl/stage/data/bytes/WrappedValueBytesData.java +++ b/src/main/java/net/openhft/chronicle/map/impl/stage/data/bytes/WrappedValueBytesData.java @@ -48,8 +48,6 @@ public class WrappedValueBytesData extends AbstractData { private boolean wrappedValueBytesUsed = false; @Stage("CachedWrappedValue") private V cachedWrappedValue; - @Stage("CachedWrappedValue") - private boolean cachedWrappedValueRead = false; boolean nextInit() { return true; @@ -102,7 +100,6 @@ void closeWrappedValueBytes() { private void initCachedWrappedValue() { cachedWrappedValue = innerGetUsing(cachedWrappedValue); - cachedWrappedValueRead = true; } @Override diff --git a/src/main/java/net/openhft/chronicle/map/locks/ChronicleStampedLock.java b/src/main/java/net/openhft/chronicle/map/locks/ChronicleStampedLock.java index d5eb9d03c..87b68ec40 100644 --- a/src/main/java/net/openhft/chronicle/map/locks/ChronicleStampedLock.java +++ b/src/main/java/net/openhft/chronicle/map/locks/ChronicleStampedLock.java @@ -173,15 +173,13 @@ public long tryConvertToWriteLock(long stamp) { @Override public long tryWriteLock() { - long l = 0L; - offHeapLock = chm.get("Stamp "); lastWriterT = chm.get("LastWriterTime "); writeLockHolderCount = chmW.get("WriterCount "); - l = offHeapLock.getEntryLockState(); + long lockState = offHeapLock.getEntryLockState(); - if (l != 0L) + if (lockState != 0L) return 0L; do { @@ -202,7 +200,7 @@ public long tryWriteLock() { "," ); offHeapLock = chm.get("Stamp "); - l = offHeapLock.getEntryLockState(); + lockState = offHeapLock.getEntryLockState(); try { Thread.sleep((long) (1000 * Math.random())); } catch (InterruptedException e) { @@ -211,10 +209,8 @@ public long tryWriteLock() { } } while ( readLockHolderCount.getVolatileValue() > 0 || - (writeLockHolderCount = - chmW.get("WriterCount ")) - .getVolatileValue() > 0 - ); + (writeLockHolderCount = chmW.get("WriterCount ")) + .getVolatileValue() > 0); writeLockHolderCount.addAtomicValue(+1); chmW.put("WriterCount ", writeLockHolderCount); @@ -306,12 +302,11 @@ public long tryReadLock() { @Override public long writeLock() { - long l = 0L; - offHeapLock = chm.get("Stamp "); lastWriterT = chm.get("LastWriterTime "); writeLockHolderCount = chmW.get("WriterCount "); + long lockState; do { Jvm.debug().on(getClass(), " ,@t=" + System.currentTimeMillis() + @@ -330,7 +325,7 @@ public long writeLock() { "," ); offHeapLock = chm.get("Stamp "); - l = offHeapLock.getEntryLockState(); + lockState = offHeapLock.getEntryLockState(); try { Thread.sleep((long) (1000 * Math.random())); } catch (InterruptedException e) { @@ -338,7 +333,7 @@ public long writeLock() { Thread.currentThread().interrupt(); } } while ( - l != 0L || + lockState != 0L || readLockHolderCount.getVolatileValue() > 0 || (writeLockHolderCount = chmW.get("WriterCount ")).getVolatileValue() > 0 ); @@ -373,11 +368,10 @@ public long writeLock() { @Override public long readLock() { - long l = 0L; - offHeapLock = chm.get("Stamp "); readLockHolderCount = chmR.get("ReaderCount "); + long lockState; do { Jvm.debug().on(getClass(), " ,@t=" + System.currentTimeMillis() + @@ -391,14 +385,14 @@ public long readLock() { "] " + "," ); - l = (offHeapLock = chm.get("Stamp ")).getEntryLockState(); + lockState = (offHeapLock = chm.get("Stamp ")).getEntryLockState(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); Thread.currentThread().interrupt(); } - } while (l < 0L); + } while (lockState < 0L); Jvm.debug().on(getClass(), " ,@t=" + System.currentTimeMillis() + @@ -437,7 +431,7 @@ public void unlock(long stamp) { } else if (stamp > 0L) { unlockRead(stamp); } else { - // lock available + return; } } diff --git a/src/main/java/net/openhft/chronicle/set/ChronicleSetBuilder.java b/src/main/java/net/openhft/chronicle/set/ChronicleSetBuilder.java index 2e56af71a..00bbe9e53 100644 --- a/src/main/java/net/openhft/chronicle/set/ChronicleSetBuilder.java +++ b/src/main/java/net/openhft/chronicle/set/ChronicleSetBuilder.java @@ -35,7 +35,6 @@ public final class ChronicleSetBuilder corruption -> Jvm.error().on(ChronicleSetBuilder.class, corruption.message(), corruption.exception()); private ChronicleMapBuilder chronicleMapBuilder; - private final ChronicleSetBuilderPrivateAPI privateAPI; ChronicleSetBuilder(Class keyClass) { chronicleMapBuilder = ChronicleMapBuilder.of(keyClass, DummyValue.class) @@ -43,7 +42,7 @@ public final class ChronicleSetBuilder DummyValueMarshaller.INSTANCE, DummyValueMarshaller.INSTANCE) .valueSizeMarshaller(SizeMarshaller.constant(0)); //noinspection deprecation,unchecked - privateAPI = new ChronicleSetBuilderPrivateAPI<>( + ChronicleSetBuilderPrivateAPI privateAPI = new ChronicleSetBuilderPrivateAPI<>( (ChronicleHashBuilderPrivateAPI>) Jvm.getValue(chronicleMapBuilder, "privateAPI")); } diff --git a/src/main/java/net/openhft/chronicle/set/SetFromMap.java b/src/main/java/net/openhft/chronicle/set/SetFromMap.java index c116bb225..db7dcbb76 100644 --- a/src/main/java/net/openhft/chronicle/set/SetFromMap.java +++ b/src/main/java/net/openhft/chronicle/set/SetFromMap.java @@ -29,7 +29,7 @@ class SetFromMap extends AbstractSet implements ChronicleSet { private final ChronicleMap m; // The backing map - private transient Set s; // Its keySet + private final transient Set s; // Its keySet SetFromMap(VanillaChronicleMap map) { m = map; diff --git a/src/main/java/net/openhft/xstream/converters/AbstractChronicleMapConverter.java b/src/main/java/net/openhft/xstream/converters/AbstractChronicleMapConverter.java index 715178ca9..aed3371ff 100644 --- a/src/main/java/net/openhft/xstream/converters/AbstractChronicleMapConverter.java +++ b/src/main/java/net/openhft/xstream/converters/AbstractChronicleMapConverter.java @@ -46,7 +46,8 @@ private static E deserialize(@NotNull UnmarshallingContext unmarshallingCont case "java.util.Collections$EmptyMap": case "java.util.Collections.EmptyMap": return (E) Collections.emptyMap(); - + default: + break; } return (E) unmarshallingContext.convertAnother(null, forName(reader.getNodeName())); diff --git a/src/main/java/net/openhft/xstream/converters/ByteBufferConverter.java b/src/main/java/net/openhft/xstream/converters/ByteBufferConverter.java index bb1279288..732433999 100644 --- a/src/main/java/net/openhft/xstream/converters/ByteBufferConverter.java +++ b/src/main/java/net/openhft/xstream/converters/ByteBufferConverter.java @@ -14,13 +14,15 @@ import java.nio.CharBuffer; import java.nio.charset.*; +import static java.nio.charset.StandardCharsets.*; + /** * Created by Rob Austin */ @SuppressWarnings({"rawtypes", "unchecked"}) public class ByteBufferConverter implements Converter { - private final Charset charset = Charset.forName("ISO-8859-1"); + private final Charset charset = ISO_8859_1; private final CharsetDecoder decoder = charset.newDecoder(); @Override @@ -47,7 +49,7 @@ public void marshal(Object o, HierarchicalStreamWriter writer, MarshallingContex buffer.capacity(); int position = buffer.position(); - int limit = buffer.limit(); + final int limit = buffer.limit(); buffer.clear(); @@ -78,7 +80,7 @@ public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext un reader.moveUp(); reader.moveDown(); - int limit = (Integer) unmarshallingContext.convertAnother(null, int.class); + final int limit = (Integer) unmarshallingContext.convertAnother(null, int.class); reader.moveUp(); reader.moveDown(); diff --git a/src/main/java/net/openhft/xstream/converters/ValueConverter.java b/src/main/java/net/openhft/xstream/converters/ValueConverter.java index eddc75b64..2cfe96a75 100644 --- a/src/main/java/net/openhft/xstream/converters/ValueConverter.java +++ b/src/main/java/net/openhft/xstream/converters/ValueConverter.java @@ -84,7 +84,7 @@ public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext co } private void fillInObject(HierarchicalStreamReader reader, UnmarshallingContext context, - ValueModel valueModel, Object using) throws ClassNotFoundException { + ValueModel valueModel, Object using) { while (reader.hasMoreChildren()) { reader.moveDown(); diff --git a/src/test/java/eg/BigData.java b/src/test/java/eg/BigData.java index f0e2f81d9..a06381b5b 100644 --- a/src/test/java/eg/BigData.java +++ b/src/test/java/eg/BigData.java @@ -20,12 +20,12 @@ vm.dirty_writeback_centisecs = 3000 */ public class BigData { - final static long MAXSIZE = 1000 * 1000 * 1000L; + static final long MAXSIZE = 1000 * 1000 * 1000L; static final ChronicleMapBuilder builder = ChronicleMapBuilder.of(Long.class, BigDataStuff.class); //run 1st test with no map, and Highwatermark set to 0 //then switch to Highwatermark set to MAXSIZE for subsequent test repeats - static AtomicInteger Highwatermark = new AtomicInteger((int) MAXSIZE); + static final AtomicInteger highWatermark = new AtomicInteger((int) MAXSIZE); static Map theMap; // static AtomicInteger Highwatermark = new AtomicInteger(0); @@ -47,37 +47,37 @@ public class BigData { public static void main(String[] args) throws IOException, InterruptedException { long start = System.currentTimeMillis(); initialbuild(); - System.out.println("Start highwatermark " + Highwatermark.get()); + System.out.println("Start highwatermark " + highWatermark.get()); for (int i = 0; i < 10; i++) { Thread t1 = new Thread("test 1") { public void run() { - _test(); + runTest(); } }; Thread t2 = new Thread("test 2") { public void run() { - _test(); + runTest(); } }; Thread t3 = new Thread("test 3") { public void run() { - _test(); + runTest(); } }; t1.start(); t2.start(); t3.start(); - _test(); + runTest(); t1.join(); t2.join(); t3.join(); } - System.out.println("End highwatermark " + Highwatermark.get()); + System.out.println("End highwatermark " + highWatermark.get()); long time = System.currentTimeMillis() - start; System.out.printf("End to end took %.1f%n", time / 1e3); } - public static void initialbuild() throws IOException, InterruptedException { + public static void initialbuild() throws InterruptedException { System.out.println("building an empty map"); long start = System.currentTimeMillis(); Thread t1 = new Thread("test 1") { @@ -123,26 +123,22 @@ public static void populate(int n) { } } - public static void _test() { + public static void runTest() { // improves logging of these threads. Affinity.setThreadId(); - try { - test(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + runPerformanceIteration(); + } - public static void test() throws IOException { + public static void runPerformanceIteration() { //do a sequence 1m of each of insert/read/update //inserts - long LOOPCOUNT = 100 * 1000L; + long loopCount = 100 * 1000L; Random rand = new Random(); long start = System.currentTimeMillis(); BigDataStuff value = new BigDataStuff(0); - for (long i = 0; i < LOOPCOUNT; i++) { - long current = rand.nextInt(Highwatermark.get()); + for (long i = 0; i < loopCount; i++) { + long current = rand.nextInt(highWatermark.get()); value.x = current; value.y.setLength(0); value.y.append(current); @@ -153,8 +149,8 @@ public static void test() throws IOException { int count = 0; start = System.currentTimeMillis(); - for (long i = 0; i < LOOPCOUNT; i++) { - long keyval = rand.nextInt(Highwatermark.get()); + for (long i = 0; i < loopCount; i++) { + long keyval = rand.nextInt(highWatermark.get()); count++; BigDataStuff stuff = theMap.get(keyval); if (stuff == null) { @@ -166,8 +162,8 @@ public static void test() throws IOException { start = System.currentTimeMillis(); count = 0; - for (long i = 0; i < LOOPCOUNT; i++) { - long keyval = rand.nextInt(Highwatermark.get()); + for (long i = 0; i < loopCount; i++) { + long keyval = rand.nextInt(highWatermark.get()); BigDataStuff stuff = theMap.get(keyval); if (stuff == null) { System.out.println("hit an empty at key " + keyval); @@ -191,6 +187,9 @@ public BigDataStuff(long x) { this.x = x; } + public BigDataStuff() { + } + @Override public void writeExternal(ObjectOutput out) throws IOException { out.writeLong(x); diff --git a/src/test/java/eg/WordCountTest.java b/src/test/java/eg/WordCountTest.java index 3e018c4bf..b0c90f95a 100644 --- a/src/test/java/eg/WordCountTest.java +++ b/src/test/java/eg/WordCountTest.java @@ -26,14 +26,14 @@ public class WordCountTest { - static String[] words; - static Map expectedMap; + static final String[] words; + static final Map expectedMap; static { // english version of war and peace -> ascii ClassLoader cl = Thread.currentThread().getContextClassLoader(); try (InputStream zippedIS = Objects.requireNonNull(cl.getResourceAsStream("war_and_peace.txt.gz")); - GZIPInputStream binaryIS = new GZIPInputStream(zippedIS);) { + GZIPInputStream binaryIS = new GZIPInputStream(zippedIS)) { String fullText = new String(ByteStreams.toByteArray(binaryIS), UTF_8); words = fullText.split("\\s+"); diff --git a/src/test/java/examples/portfolio/PortfolioAssetInterface.java b/src/test/java/examples/portfolio/PortfolioAssetInterface.java index 441f2050c..219345cbe 100644 --- a/src/test/java/examples/portfolio/PortfolioAssetInterface.java +++ b/src/test/java/examples/portfolio/PortfolioAssetInterface.java @@ -4,15 +4,15 @@ package examples.portfolio; public interface PortfolioAssetInterface { - public long getAssetId(); + long getAssetId(); - public void setAssetId(long assetId); + void setAssetId(long assetId); - public int getShares(); + int getShares(); - public void setShares(int shares); + void setShares(int shares); - public double getPrice(); + double getPrice(); - public void setPrice(double price); + void setPrice(double price); } diff --git a/src/test/java/net/openhft/chronicle/hash/serialization/impl/ByteBufferDataAccessTest.java b/src/test/java/net/openhft/chronicle/hash/serialization/impl/ByteBufferDataAccessTest.java index 22ca8cb87..602134cf4 100644 --- a/src/test/java/net/openhft/chronicle/hash/serialization/impl/ByteBufferDataAccessTest.java +++ b/src/test/java/net/openhft/chronicle/hash/serialization/impl/ByteBufferDataAccessTest.java @@ -24,8 +24,8 @@ public void getUsingTest() { Data data1 = bbDataAccess.getData(bb1); ByteBuffer bb2 = ByteBuffer.allocate(2); data1.getUsing(bb2); - assertEquals(bb2.get(0), 3); - assertEquals(bb2.get(1), 4); + assertEquals(3, bb2.get(0)); + assertEquals(4, bb2.get(1)); } @Test diff --git a/src/test/java/net/openhft/chronicle/map/AbstractMarshallableKeyValueTest.java b/src/test/java/net/openhft/chronicle/map/AbstractMarshallableKeyValueTest.java index 5b7fbaf28..cda2c13eb 100644 --- a/src/test/java/net/openhft/chronicle/map/AbstractMarshallableKeyValueTest.java +++ b/src/test/java/net/openhft/chronicle/map/AbstractMarshallableKeyValueTest.java @@ -14,7 +14,7 @@ public final class AbstractMarshallableKeyValueTest { @Test - public void shouldAcceptAbstractMarshallableComponents() throws Exception { + public void shouldAcceptAbstractMarshallableComponents() { final ChronicleMap map = ChronicleMapBuilder.of(Key.class, Value.class).entries(10). averageKey(new Key()).averageValue(new Value()).create(); @@ -24,7 +24,7 @@ public void shouldAcceptAbstractMarshallableComponents() throws Exception { } @Test - public void shouldAcceptAbstractMarshallableComponents2() throws Exception { + public void shouldAcceptAbstractMarshallableComponents2() { final ChronicleMap map = ChronicleMapBuilder.of(Key.class, Marshallable.class).entries(10) .averageKey(new Key()).averageValue(new Value()) .valueMarshaller(new TypedMarshallableReaderWriter<>(Marshallable.class)) @@ -37,10 +37,10 @@ public void shouldAcceptAbstractMarshallableComponents2() throws Exception { } private static final class Key extends SelfDescribingMarshallable { - private String k = "key"; + private final String k = "key"; } private static final class Value extends SelfDescribingMarshallable { - private Integer number = 17; + private final Integer number = 17; } } diff --git a/src/test/java/net/openhft/chronicle/map/AcquireGetUsingMain.java b/src/test/java/net/openhft/chronicle/map/AcquireGetUsingMain.java index f2918cc95..b2cf65b0b 100644 --- a/src/test/java/net/openhft/chronicle/map/AcquireGetUsingMain.java +++ b/src/test/java/net/openhft/chronicle/map/AcquireGetUsingMain.java @@ -71,7 +71,7 @@ public static void main(String[] args) throws IOException { System.out.println("2 " + data.getTimeAt(1)); } - public static interface Data { + public interface Data { @Array(length = 8) void setTimeAt(int index, long time); diff --git a/src/test/java/net/openhft/chronicle/map/AutoResizeTest.java b/src/test/java/net/openhft/chronicle/map/AutoResizeTest.java index 9eae1af02..af86b0039 100644 --- a/src/test/java/net/openhft/chronicle/map/AutoResizeTest.java +++ b/src/test/java/net/openhft/chronicle/map/AutoResizeTest.java @@ -70,6 +70,6 @@ public void testAutoResizeNotZeroUponRestart2() { @Test(expected = IllegalArgumentException.class) public void testNegativeReplication() { - ChronicleMapBuilder.of(String.class, String.class).replication((byte) -1); + ChronicleMapBuilder.of(String.class, String.class).replication((byte) -1); } } diff --git a/src/test/java/net/openhft/chronicle/map/BasicReplicationTest.java b/src/test/java/net/openhft/chronicle/map/BasicReplicationTest.java index 00cfe531a..0a07aee02 100644 --- a/src/test/java/net/openhft/chronicle/map/BasicReplicationTest.java +++ b/src/test/java/net/openhft/chronicle/map/BasicReplicationTest.java @@ -150,6 +150,8 @@ void processPendingChangesLoop() { for (IteratorAndDestinationMap iteratorAndDestinationMap : destinationMaps) { while (iteratorAndDestinationMap.modificationIterator.nextEntry( iteratorAndDestinationMap, sourceMap.identifier())) { + // drain all pending entries + continue; } } diff --git a/src/test/java/net/openhft/chronicle/map/BooleanValuesTest.java b/src/test/java/net/openhft/chronicle/map/BooleanValuesTest.java index fb8d79830..334bf83c1 100644 --- a/src/test/java/net/openhft/chronicle/map/BooleanValuesTest.java +++ b/src/test/java/net/openhft/chronicle/map/BooleanValuesTest.java @@ -6,8 +6,6 @@ import org.junit.Assert; import org.junit.Test; -import java.io.IOException; - /** * @author Rob Austin. */ @@ -17,7 +15,7 @@ public class BooleanValuesTest { * see issue here */ @Test - public void testTestBooleanValues() throws IOException, InterruptedException { + public void testTestBooleanValues() { try (ChronicleMap map = ChronicleMap.of(Integer.class, Boolean.class) .entries(1).create()) { map.put(7, true); diff --git a/src/test/java/net/openhft/chronicle/map/BuildVersionTest.java b/src/test/java/net/openhft/chronicle/map/BuildVersionTest.java index b1b39aa8b..2358fdc87 100644 --- a/src/test/java/net/openhft/chronicle/map/BuildVersionTest.java +++ b/src/test/java/net/openhft/chronicle/map/BuildVersionTest.java @@ -7,15 +7,13 @@ import org.junit.Assert; import org.junit.Test; -import java.io.IOException; - /** * @author Rob Austin. */ public class BuildVersionTest { @Test - public void test() throws IOException, InterruptedException { + public void test() { // checks that we always get a version Assert.assertNotNull(BuildVersion.version()); } @@ -25,7 +23,7 @@ public void test() throws IOException, InterruptedException { * */ @Test - public void testVersion() throws IOException, InterruptedException { + public void testVersion() { try (ChronicleMap expected = ChronicleMap.of(Integer.class, Double.class) .entries(1).create()) { diff --git a/src/test/java/net/openhft/chronicle/map/BytesMarshallableValueTest.java b/src/test/java/net/openhft/chronicle/map/BytesMarshallableValueTest.java index 7d6ae35ea..f72b95167 100644 --- a/src/test/java/net/openhft/chronicle/map/BytesMarshallableValueTest.java +++ b/src/test/java/net/openhft/chronicle/map/BytesMarshallableValueTest.java @@ -23,8 +23,8 @@ public void bytesMarshallableValueTest() { } public static class Value implements BytesMarshallable { - int x; - String foo; + final int x; + final String foo; public Value(int x, String foo) { this.x = x; diff --git a/src/test/java/net/openhft/chronicle/map/CHMLatencyTestMain.java b/src/test/java/net/openhft/chronicle/map/CHMLatencyTestMain.java index 4409f63da..5d09745c6 100644 --- a/src/test/java/net/openhft/chronicle/map/CHMLatencyTestMain.java +++ b/src/test/java/net/openhft/chronicle/map/CHMLatencyTestMain.java @@ -59,7 +59,7 @@ public class CHMLatencyTestMain { public static void main(String... ignored) throws IOException { AffinityLock lock = AffinityLock.acquireCore(); File file = File.createTempFile("testCHMLatency", "deleteme"); -// File file = new File("testCHMLatency.deleteme"); + // File file = new File("testCHMLatency.deleteme"); file.delete(); ChronicleMap countersMap = ChronicleMapBuilder.of(LongValue.class, LongValue.class) @@ -75,7 +75,7 @@ public static void main(String... ignored) throws IOException { value.setValue(0); } System.out.println("Keys created"); -// Monitor monitor = new Monitor(); + // Monitor monitor = new Monitor(); LongValue value2 = Values.newNativeReference(LongValue.class); for (int t = 0; t < 5; t++) { for (int rate : new int[]{2 * 1000 * 1000, 1000 * 1000, 500 * 1000/*, 250 * 1000, 100 * 1000, 50 * 1000*/}) { @@ -89,9 +89,9 @@ public static void main(String... ignored) throws IOException { // the timed part for (int i = 0; i < KEYS && u < RUN_TIME * rate; i += stride) { // busy wait for next time. - while (System.nanoTime() < next - 12) ; -// monitor.sample = System.nanoTime(); - long start0 = next; + while (System.nanoTime() < next - 12) + Thread.yield(); + final long start0 = next; // start the update. key.setValue(i); @@ -105,22 +105,22 @@ public static void main(String... ignored) throws IOException { times.sample(elapse); next += delay; } -// monitor.sample = Long.MAX_VALUE; + // monitor.sample = Long.MAX_VALUE; } System.out.printf("run %d %,9d : ", t, rate); times.printPercentiles(" micro-seconds."); } System.out.println(); } -// monitor.running = false; + // monitor.running = false; countersMap.close(); file.delete(); } static class Monitor implements Runnable { final Thread thread; - volatile boolean running = true; - volatile long sample; + final boolean running = true; + final long sample; Monitor() { this.thread = Thread.currentThread(); diff --git a/src/test/java/net/openhft/chronicle/map/CHMTestIterator1.java b/src/test/java/net/openhft/chronicle/map/CHMTestIterator1.java index 6b3f1dc73..978492119 100644 --- a/src/test/java/net/openhft/chronicle/map/CHMTestIterator1.java +++ b/src/test/java/net/openhft/chronicle/map/CHMTestIterator1.java @@ -20,12 +20,12 @@ public static void main(String[] args) { .entries(runs); try (ChronicleMap chm = builder.create()) { - /*chm.put("k1", alValue.incrementAndGet()); - chm.put("k2", alValue.incrementAndGet()); - chm.put("k3", alValue.incrementAndGet()); - chm.put("k4", alValue.incrementAndGet()); - chm.put("k5", alValue.incrementAndGet());*/ - //chm.keySet(); + // chm.put("k1", alValue.incrementAndGet()); + // chm.put("k2", alValue.incrementAndGet()); + // chm.put("k3", alValue.incrementAndGet()); + // chm.put("k4", alValue.incrementAndGet()); + // chm.put("k5", alValue.incrementAndGet()); + // chm.keySet(); for (int i = 0; i < runs; i++) { chm.put("k" + alKey.incrementAndGet(), alValue.incrementAndGet()); diff --git a/src/test/java/net/openhft/chronicle/map/CHMUseCasesTest.java b/src/test/java/net/openhft/chronicle/map/CHMUseCasesTest.java index ac310a341..c55c736a7 100644 --- a/src/test/java/net/openhft/chronicle/map/CHMUseCasesTest.java +++ b/src/test/java/net/openhft/chronicle/map/CHMUseCasesTest.java @@ -136,6 +136,7 @@ interface Inner { } } + /** * This test enumerates common use cases for keys and values. */ @@ -219,7 +220,9 @@ else if (map1.valueClass() == byte[][].class) { for (int i = 0; i < o1.length; i++) { Assert.assertArrayEquals(o1[i], o2[i]); } - } else throw new IllegalStateException("unsupported type"); + } else { + throw new IllegalStateException("unsupported type"); + } } } @@ -501,7 +504,7 @@ public void testStringStringMap() throws assertEquals("World", map.get("Hello")); assertEquals("New World", map.getMapped("Hello", new PrefixStringFunction("New "))); - assertEquals(null, map.getMapped("No key", new PrefixStringFunction("New "))); + assertNull(map.getMapped("No key", new PrefixStringFunction("New "))); mapChecks(); } } @@ -582,7 +585,7 @@ public void testCharSequenceCharSequenceMap() assertNull(map.getUsing(key, value)); assertEquals("New World", map.getMapped("Hello", s -> "New " + s)); - assertEquals(null, map.getMapped("No key", + assertNull(map.getMapped("No key", (SerializableFunction) s -> "New " + s)); assertEquals("New World !!", map.computeIfPresent("Hello", (k, s) -> { @@ -635,7 +638,7 @@ public void testGetUsingWithIntValueNoValue() throws IOException { assertNull(c.entry()); } - assertEquals(null, map.get("1")); + assertNull(map.get("1")); mapChecks(); } } @@ -657,19 +660,19 @@ public void testAcquireUsingImmutableUsing() throws IOException { using.setValue(1); } - assertEquals(null, map.get("1")); + assertNull(map.get("1")); mapChecks(); } } @Test(expected = IllegalArgumentException.class) public void testNegativeActualChunkSize() { - ChronicleMapBuilder.of(String.class, String.class).actualChunkSize(-1); + ChronicleMapBuilder.of(String.class, String.class).actualChunkSize(-1); } @Test(expected = IllegalArgumentException.class) public void testActualChunksPerSegmentTier() { - ChronicleMapBuilder.of(String.class, String.class).actualChunksPerSegmentTier(0); + ChronicleMapBuilder.of(String.class, String.class).actualChunksPerSegmentTier(0); } @Test @@ -737,9 +740,9 @@ public void testStringValueStringValueMap() throws IOException { try (ChronicleMap map = newInstance(builder)) { StringValue key1 = Values.newHeapInstance(StringValue.class); - StringValue key2 = Values.newHeapInstance(StringValue.class); + final StringValue key2 = Values.newHeapInstance(StringValue.class); StringValue value1 = Values.newHeapInstance(StringValue.class); - StringValue value2 = Values.newHeapInstance(StringValue.class); + final StringValue value2 = Values.newHeapInstance(StringValue.class); key1.setValue(new StringBuilder("1")); value1.setValue("11"); @@ -876,9 +879,9 @@ public void testIntegerIntegerMap() assertEquals(1, ((VanillaChronicleMap) map).maxChunksPerEntry); Integer key1; - Integer key2; + final Integer key2; Integer value1; - Integer value2; + final Integer value2; key1 = 1; value1 = 11; @@ -892,8 +895,8 @@ public void testIntegerIntegerMap() assertEquals((Integer) 11, map.get(key1)); assertEquals((Integer) 22, map.get(key2)); - assertEquals(null, map.get(3)); - assertEquals(null, map.get(4)); + assertNull(map.get(3)); + assertNull(map.get(4)); mapChecks(); @@ -906,7 +909,7 @@ public Integer apply(Integer s) { mapChecks(); - assertEquals(null, map.getMapped(-1, new SerializableFunction() { + assertNull(map.getMapped(-1, new SerializableFunction() { @Override public Integer apply(Integer s) { return 10 * s; @@ -918,6 +921,7 @@ public Integer apply(Integer s) { try { map.computeIfPresent(1, (k, s) -> s + 1); } catch (Exception todoMoreSpecificException) { + assertNotNull(todoMoreSpecificException); } mapChecks(); @@ -932,16 +936,16 @@ public void testLongLongMap() throws IOException { .entries(10); try (ChronicleMap map = newInstance(builder)) { -// assertEquals(16, entrySize(map)); -// assertEquals(1, ((VanillaChronicleMap) map).maxChunksPerEntry); + // assertEquals(16, entrySize(map)); + // assertEquals(1, ((VanillaChronicleMap) map).maxChunksPerEntry); map.put(1L, 11L); assertEquals((Long) 11L, map.get(1L)); map.put(2L, 22L); assertEquals((Long) 22L, map.get(2L)); - assertEquals(null, map.get(3L)); - assertEquals(null, map.get(4L)); + assertNull(map.get(3L)); + assertNull(map.get(4L)); mapChecks(); @@ -951,13 +955,14 @@ public Long apply(Long s) { return 10 * s; } })); - assertEquals(null, map.getMapped(-1L, (SerializableFunction) s -> 10 * s)); + assertNull(map.getMapped(-1L, (SerializableFunction) s -> 10 * s)); mapChecks(); try { map.computeIfPresent(1L, (k, s) -> s + 1); } catch (Exception todoMoreSpecificException) { + assertNotNull(todoMoreSpecificException); } mapChecks(); @@ -980,8 +985,8 @@ public void testDoubleDoubleMap() throws IOException { map.put(2.0, 22.0); assertEquals((Double) 22.0, map.get(2.0)); - assertEquals(null, map.get(3.0)); - assertEquals(null, map.get(4.0)); + assertNull(map.get(3.0)); + assertNull(map.get(4.0)); assertEquals((Double) 110.0, map.getMapped(1.0, new SerializableFunction() { @Override @@ -989,12 +994,13 @@ public Double apply(Double s) { return 10 * s; } })); - assertEquals(null, map.getMapped(-1.0, (SerializableFunction) s -> 10 * s)); + assertNull(map.getMapped(-1.0, (SerializableFunction) s -> 10 * s)); try { map.computeIfPresent(1.0, (k, s) -> s + 1); } catch (Exception todoMoreSpecificException) { + assertNotNull(todoMoreSpecificException); } } } @@ -1009,39 +1015,37 @@ public void testByteArrayByteArrayMap() try (ChronicleMap map = newInstance(builder)) { byte[] key1 = {1, 1, 1, 1}; - byte[] key2 = {2, 2, 2, 2}; + final byte[] key2 = {2, 2, 2, 2}; byte[] value1 = {11, 11, 11, 11}; - byte[] value2 = {22, 22, 22, 22}; + final byte[] value2 = {22, 22, 22, 22}; assertNull(map.put(key1, value1)); - assertTrue(Arrays.equals(value1, map.put(key1, value2))); - assertTrue(Arrays.equals(value2, map.get(key1))); + assertArrayEquals(value1, map.put(key1, value2)); + assertArrayEquals(value2, map.get(key1)); assertNull(map.get(key2)); map.put(key1, value1); - assertTrue(Arrays.equals(new byte[]{11, 11}, - map.getMapped(key1, new SerializableFunction() { - @Override - public byte[] apply(byte[] s) { - return Arrays.copyOf(s, 2); - } - }))); - assertEquals(null, map.getMapped(key2, new SerializableFunction() { + assertArrayEquals(new byte[]{11, 11}, map.getMapped(key1, new SerializableFunction() { + @Override + public byte[] apply(byte[] s) { + return Arrays.copyOf(s, 2); + } + })); + assertNull(map.getMapped(key2, new SerializableFunction() { @Override public byte[] apply(byte[] s) { return Arrays.copyOf(s, 2); } })); - assertTrue(Arrays.equals(new byte[]{12, 10}, - map.computeIfPresent(key1, (k, s) -> { - s[0]++; - s[1]--; - return Arrays.copyOf(s, 2); - }))); + assertArrayEquals(new byte[]{12, 10}, map.computeIfPresent(key1, (k, s) -> { + s[0]++; + s[1]--; + return Arrays.copyOf(s, 2); + })); byte[] a2 = map.get(key1); - assertTrue(Arrays.equals(new byte[]{12, 10}, a2)); + assertArrayEquals(new byte[]{12, 10}, a2); } } @@ -1058,10 +1062,10 @@ public void testByteBufferByteBufferDefaultKeyValueMarshaller() throws try (ChronicleMap map = newInstance(builder)) { - ByteBuffer key1 = ByteBuffer.wrap(new byte[]{1, 1, 1, 1}); - ByteBuffer key2 = ByteBuffer.wrap(new byte[]{2, 2, 2, 2}); - ByteBuffer value1 = ByteBuffer.wrap(new byte[]{11, 11, 11, 11}); - ByteBuffer value2 = ByteBuffer.wrap(new byte[]{22, 22, 22, 22}); + final ByteBuffer key1 = ByteBuffer.wrap(new byte[]{1, 1, 1, 1}); + final ByteBuffer key2 = ByteBuffer.wrap(new byte[]{2, 2, 2, 2}); + final ByteBuffer value1 = ByteBuffer.wrap(new byte[]{11, 11, 11, 11}); + final ByteBuffer value2 = ByteBuffer.wrap(new byte[]{22, 22, 22, 22}); assertNull(map.put(key1, value1)); assertBBEquals(value1, map.put(key1, value2)); assertBBEquals(value2, map.get(key1)); @@ -1086,9 +1090,9 @@ public void testByteBufferByteBufferMap() try (ChronicleMap map = newInstance(builder)) { ByteBuffer key1 = ByteBuffer.wrap(new byte[]{1, 1, 1, 1}).order(ByteOrder.nativeOrder()); - ByteBuffer key2 = ByteBuffer.wrap(new byte[]{2, 2, 2, 2}).order(ByteOrder.nativeOrder()); + final ByteBuffer key2 = ByteBuffer.wrap(new byte[]{2, 2, 2, 2}).order(ByteOrder.nativeOrder()); ByteBuffer value1 = ByteBuffer.wrap(new byte[]{11, 11, 11, 11}).order(ByteOrder.nativeOrder()); - ByteBuffer value2 = ByteBuffer.wrap(new byte[]{22, 22, 22, 22}).order(ByteOrder.nativeOrder()); + final ByteBuffer value2 = ByteBuffer.wrap(new byte[]{22, 22, 22, 22}).order(ByteOrder.nativeOrder()); assertNull(map.put(key1, value1)); assertBBEquals(value1, map.put(key1, value2)); assertBBEquals(value2, map.get(key1)); @@ -1106,7 +1110,7 @@ public ByteBuffer apply(ByteBuffer s) { map.put(key1, value1); assertBBEquals(ByteBuffer.wrap(new byte[]{11, 11}), map.getMapped(key1, function)); - assertEquals(null, map.getMapped(key2, function)); + assertNull(map.getMapped(key2, function)); mapChecks(); assertBBEquals(ByteBuffer.wrap(new byte[]{12, 10}), map.computeIfPresent(key1, (k, s) -> { @@ -1123,7 +1127,7 @@ public ByteBuffer apply(ByteBuffer s) { map.put(key2, value2); ByteBuffer valueA = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); ByteBuffer valueB = ByteBuffer.allocate(8).order(ByteOrder.nativeOrder()); -// assertBBEquals(value1, valueA); + // assertBBEquals(value1, valueA); try (ExternalMapQueryContext c = map.queryContext(key1)) { MapEntry entry = c.entry(); assertNotNull(entry); @@ -1263,12 +1267,12 @@ public void testIntValueIntValueMap() throws IOException { try (ChronicleMap map = newInstance(builder)) { // this may change due to alignment -// assertEquals(8, entrySize(map)); + // assertEquals(8, entrySize(map)); assertEquals(1, ((VanillaChronicleMap) map).maxChunksPerEntry); - IntValue key1 = Values.newHeapInstance(IntValue.class); - IntValue key2 = Values.newHeapInstance(IntValue.class); - IntValue value1 = Values.newHeapInstance(IntValue.class); - IntValue value2 = Values.newHeapInstance(IntValue.class); + final IntValue key1 = Values.newHeapInstance(IntValue.class); + final IntValue key2 = Values.newHeapInstance(IntValue.class); + final IntValue value1 = Values.newHeapInstance(IntValue.class); + final IntValue value2 = Values.newHeapInstance(IntValue.class); key1.setValue(1); value1.setValue(11); @@ -1287,10 +1291,6 @@ public void testIntValueIntValueMap() throws IOException { } // TODO review -- the previous version of this block: // acquiring for value1, comparing value2 -- as intended? -// try (ReadContext rc = map.getUsingLocked(key2, value1)) { -// assertTrue(rc.present()); -// assertEquals(22, value2.getValue()); -// } try (ExternalMapQueryContext c = map.queryContext(key2)) { MapEntry entry = c.entry(); assertNotNull(entry); @@ -1377,15 +1377,16 @@ public void testUnsignedIntValueUnsignedIntValueMap() throws IOException { assertEquals(value1, map.get(key1)); key1 = Values.newHeapInstance(UnsignedIntValue.class); - UnsignedIntValue key2 = Values.newHeapInstance(UnsignedIntValue.class); value1 = Values.newHeapInstance(UnsignedIntValue.class); - UnsignedIntValue value2 = Values.newHeapInstance(UnsignedIntValue.class); key1.setValue(1); value1.setValue(11); map.put(key1, value1); assertEquals(value1, map.get(key1)); + UnsignedIntValue key2 = Values.newHeapInstance(UnsignedIntValue.class); + UnsignedIntValue value2 = Values.newHeapInstance(UnsignedIntValue.class); + key2.setValue(2); value2.setValue(22); map.put(key2, value2); @@ -1398,10 +1399,6 @@ public void testUnsignedIntValueUnsignedIntValueMap() throws IOException { assertEquals(11, entry.value().get().getValue()); } // TODO review suspicious block -// try (ReadContext rc = map.getUsingLocked(key2, value1)) { -// assertTrue(rc.present()); -// assertEquals(22, value2.getValue()); -// } try (ExternalMapQueryContext c = map.queryContext(key2)) { MapEntry entry = c.entry(); @@ -1488,10 +1485,10 @@ public void testIntValueShortValueMap() throws IOException { // assertEquals(6, entrySize(map)); // assertEquals(1, ((VanillaChronicleMap) map).maxChunksPerEntry); - IntValue key1 = Values.newHeapInstance(IntValue.class); - IntValue key2 = Values.newHeapInstance(IntValue.class); - ShortValue value1 = Values.newHeapInstance(ShortValue.class); - ShortValue value2 = Values.newHeapInstance(ShortValue.class); + final IntValue key1 = Values.newHeapInstance(IntValue.class); + final IntValue key2 = Values.newHeapInstance(IntValue.class); + final ShortValue value1 = Values.newHeapInstance(ShortValue.class); + final ShortValue value2 = Values.newHeapInstance(ShortValue.class); key1.setValue(1); value1.setValue((short) 11); @@ -1509,10 +1506,10 @@ public void testIntValueShortValueMap() throws IOException { assertEquals(11, entry.value().get().getValue()); } // TODO the same as above. -// try (ReadContext rc = map.getUsingLocked(key2, value1)) { -// assertTrue(rc.present()); -// assertEquals(22, value2.getValue()); -// } + // try (ReadContext rc = map.getUsingLocked(key2, value1)) { + // assertTrue(rc.present()); + // assertEquals(22, value2.getValue()); + // } try (ExternalMapQueryContext c = map.queryContext(key2)) { MapEntry entry = c.entry(); assertNotNull(entry); @@ -1594,15 +1591,16 @@ public void testIntValueUnsignedShortValueMap() throws IOException { // assertEquals(8, entrySize(map)); assertEquals(1, ((VanillaChronicleMap) map).maxChunksPerEntry); IntValue key1 = Values.newHeapInstance(IntValue.class); - IntValue key2 = Values.newHeapInstance(IntValue.class); UnsignedShortValue value1 = Values.newHeapInstance(UnsignedShortValue.class); - UnsignedShortValue value2 = Values.newHeapInstance(UnsignedShortValue.class); key1.setValue(1); value1.setValue(11); map.put(key1, value1); assertEquals(value1, map.get(key1)); + IntValue key2 = Values.newHeapInstance(IntValue.class); + UnsignedShortValue value2 = Values.newHeapInstance(UnsignedShortValue.class); + key2.setValue(2); value2.setValue(22); map.put(key2, value2); @@ -1614,10 +1612,6 @@ public void testIntValueUnsignedShortValueMap() throws IOException { assertEquals(11, entry.value().get().getValue()); } // TODO the same as above. -// try (ReadContext rc = map.getUsingLocked(key2, value1)) { -// assertTrue(rc.present()); -// assertEquals(22, value2.getValue()); -// } try (ExternalMapQueryContext c = map.queryContext(key2)) { MapEntry entry = c.entry(); assertNotNull(entry); @@ -1696,15 +1690,16 @@ public void testIntValueCharValueMap() throws IOException { assertEquals(1, ((VanillaChronicleMap) map).maxChunksPerEntry); IntValue key1 = Values.newHeapInstance(IntValue.class); - IntValue key2 = Values.newHeapInstance(IntValue.class); CharValue value1 = Values.newHeapInstance(CharValue.class); - CharValue value2 = Values.newHeapInstance(CharValue.class); key1.setValue(1); value1.setValue((char) 11); map.put(key1, value1); assertEquals(value1, map.get(key1)); + IntValue key2 = Values.newHeapInstance(IntValue.class); + CharValue value2 = Values.newHeapInstance(CharValue.class); + key2.setValue(2); value2.setValue((char) 22); map.put(key2, value2); @@ -1716,10 +1711,6 @@ public void testIntValueCharValueMap() throws IOException { assertEquals(11, entry.value().get().getValue()); } // TODO The same as above -// try (ReadContext rc = map.getUsingLocked(key2, value1)) { -// assertTrue(rc.present()); -// assertEquals(22, value2.getValue()); -// } try (ExternalMapQueryContext c = map.queryContext(key2)) { MapEntry entry = c.entry(); assertNotNull(entry); @@ -1799,15 +1790,16 @@ public void testIntValueUnsignedByteMap() throws IOException { assertEquals(1, ((VanillaChronicleMap) map).maxChunksPerEntry); IntValue key1 = Values.newHeapInstance(IntValue.class); - IntValue key2 = Values.newHeapInstance(IntValue.class); UnsignedByteValue value1 = Values.newHeapInstance(UnsignedByteValue.class); - UnsignedByteValue value2 = Values.newHeapInstance(UnsignedByteValue.class); key1.setValue(1); value1.setValue(11); map.put(key1, value1); assertEquals(value1, map.get(key1)); + IntValue key2 = Values.newHeapInstance(IntValue.class); + UnsignedByteValue value2 = Values.newHeapInstance(UnsignedByteValue.class); + key2.setValue(2); value2.setValue(22); map.put(key2, value2); @@ -1819,10 +1811,6 @@ public void testIntValueUnsignedByteMap() throws IOException { assertEquals(11, entry.value().get().getValue()); } // TODO the same as above -// try (ReadContext rc = map.getUsingLocked(key2, value1)) { -// assertTrue(rc.present()); -// assertEquals(22, value2.getValue()); -// } try (ExternalMapQueryContext c = map.queryContext(key2)) { MapEntry entry = c.entry(); assertNotNull(entry); @@ -1901,15 +1889,16 @@ public void testIntValueBooleanValueMap() throws IOException { assertEquals(1, ((VanillaChronicleMap) map).maxChunksPerEntry); IntValue key1 = Values.newHeapInstance(IntValue.class); - IntValue key2 = Values.newHeapInstance(IntValue.class); BooleanValue value1 = Values.newHeapInstance(BooleanValue.class); - BooleanValue value2 = Values.newHeapInstance(BooleanValue.class); key1.setValue(1); value1.setValue(true); map.put(key1, value1); assertEquals(value1, map.get(key1)); + IntValue key2 = Values.newHeapInstance(IntValue.class); + BooleanValue value2 = Values.newHeapInstance(BooleanValue.class); + key2.setValue(2); value2.setValue(false); map.put(key2, value2); @@ -1918,27 +1907,23 @@ public void testIntValueBooleanValueMap() throws IOException { try (ExternalMapQueryContext c = map.queryContext(key1)) { MapEntry entry = c.entry(); assertNotNull(entry); - assertEquals(true, entry.value().get().getValue()); + assertTrue(entry.value().get().getValue()); } // TODO the same as above. copy paste, copy paste, copy-paste... -// try (ReadContext rc = map.getUsingLocked(key2, value1)) { -// assertTrue(rc.present()); -// assertEquals(false, value2.getValue()); -// } try (ExternalMapQueryContext c = map.queryContext(key2)) { MapEntry entry = c.entry(); assertNotNull(entry); - assertEquals(false, entry.value().get().getValue()); + assertFalse(entry.value().get().getValue()); } try (ExternalMapQueryContext c = map.queryContext(key1)) { MapEntry entry = c.entry(); assertNotNull(entry); - assertEquals(true, entry.value().get().getValue()); + assertTrue(entry.value().get().getValue()); } try (ExternalMapQueryContext c = map.queryContext(key2)) { MapEntry entry = c.entry(); assertNotNull(entry); - assertEquals(false, entry.value().get().getValue()); + assertFalse(entry.value().get().getValue()); } key1.setValue(3); try (ExternalMapQueryContext c = map.queryContext(key1)) { @@ -1951,38 +1936,38 @@ public void testIntValueBooleanValueMap() throws IOException { try (net.openhft.chronicle.core.io.Closeable c = map.acquireContext(key1, value1)) { - assertEquals(false, value1.getValue()); + assertFalse(value1.getValue()); value1.setValue(true); - assertEquals(true, value1.getValue()); + assertTrue(value1.getValue()); } try (net.openhft.chronicle.core.io.Closeable c = map.acquireContext(key1, value2)) { - assertEquals(true, value2.getValue()); + assertTrue(value2.getValue()); value2.setValue(false); - assertEquals(false, value2.getValue()); + assertFalse(value2.getValue()); } try (ExternalMapQueryContext c = map.queryContext(key1)) { MapEntry entry = c.entry(); assertNotNull(entry); - assertEquals(false, entry.value().get().getValue()); + assertFalse(entry.value().get().getValue()); } try (net.openhft.chronicle.core.io.Closeable c = map.acquireContext(key2, value2)) { - assertEquals(false, value2.getValue()); + assertFalse(value2.getValue()); value2.setValue(true); - assertEquals(true, value2.getValue()); + assertTrue(value2.getValue()); } try (net.openhft.chronicle.core.io.Closeable c = map.acquireContext(key2, value1)) { - assertEquals(true, value1.getValue()); + assertTrue(value1.getValue()); value1.setValue(false); - assertEquals(false, value1.getValue()); + assertFalse(value1.getValue()); } try (ExternalMapQueryContext c = map.queryContext(key2)) { MapEntry entry = c.entry(); assertNotNull(entry); - assertEquals(false, entry.value().get().getValue()); + assertFalse(entry.value().get().getValue()); } mapChecks(); } @@ -2003,15 +1988,16 @@ public void testFloatValueFloatValueMap() throws IOException { assertEquals(1, ((VanillaChronicleMap) map).maxChunksPerEntry); FloatValue key1 = Values.newHeapInstance(FloatValue.class); - FloatValue key2 = Values.newHeapInstance(FloatValue.class); FloatValue value1 = Values.newHeapInstance(FloatValue.class); - FloatValue value2 = Values.newHeapInstance(FloatValue.class); key1.setValue(1); value1.setValue(11); map.put(key1, value1); assertEquals(value1, map.get(key1)); + FloatValue key2 = Values.newHeapInstance(FloatValue.class); + FloatValue value2 = Values.newHeapInstance(FloatValue.class); + key2.setValue(2); value2.setValue(22); map.put(key2, value2); @@ -2023,10 +2009,6 @@ public void testFloatValueFloatValueMap() throws IOException { assertEquals(11, entry.value().get().getValue(), 0); } // TODO see above -// try (ReadContext rc = map.getUsingLocked(key2, value1)) { -// assertTrue(rc.present()); -// assertEquals(22, value2.getValue(), 0); -// } try (ExternalMapQueryContext c = map.queryContext(key2)) { MapEntry entry = c.entry(); assertNotNull(entry); @@ -2108,18 +2090,19 @@ public void testDoubleValueDoubleValueMap() throws IOException { assertEquals(1, ((VanillaChronicleMap) map).maxChunksPerEntry); DoubleValue key1 = Values.newHeapInstance(DoubleValue.class); - DoubleValue key2 = Values.newHeapInstance(DoubleValue.class); DoubleValue value1 = Values.newHeapInstance(DoubleValue.class); - DoubleValue value2 = Values.newHeapInstance(DoubleValue.class); key1.setValue(1); value1.setValue(11); - assertEquals(null, map.get(key1)); + assertNull(map.get(key1)); map.put(key1, value1); DoubleValue v2 = map.get(key1); assertEquals(value1, v2); + DoubleValue key2 = Values.newHeapInstance(DoubleValue.class); + DoubleValue value2 = Values.newHeapInstance(DoubleValue.class); + key2.setValue(2); value2.setValue(22); map.put(key2, value2); @@ -2130,10 +2113,6 @@ public void testDoubleValueDoubleValueMap() throws IOException { assertNotNull(entry); assertEquals(11, entry.value().get().getValue(), 0); } -// try (ReadContext rc = map.getUsingLocked(key2, value1)) { -// assertTrue(rc.present()); -// assertEquals(22, value2.getValue(), 0); -// } try (ExternalMapQueryContext c = map.queryContext(key2)) { MapEntry entry = c.entry(); assertNotNull(entry); @@ -2214,15 +2193,16 @@ public void testLongValueLongValueMap() throws IOException { assertEquals(1, ((VanillaChronicleMap) map).maxChunksPerEntry); LongValue key1 = Values.newHeapInstance(LongValue.class); - LongValue key2 = Values.newHeapInstance(LongValue.class); LongValue value1 = Values.newHeapInstance(LongValue.class); - LongValue value2 = Values.newHeapInstance(LongValue.class); key1.setValue(1); value1.setValue(11); - assertEquals(null, map.get(key1)); + assertNull(map.get(key1)); map.put(key1, value1); + LongValue key2 = Values.newHeapInstance(LongValue.class); + LongValue value2 = Values.newHeapInstance(LongValue.class); + key2.setValue(2); value2.setValue(22); map.put(key2, value2); @@ -2234,10 +2214,6 @@ public void testLongValueLongValueMap() throws IOException { assertEquals(11, entry.value().get().getValue()); } // TODO see above -// try (ReadContext rc = map.getUsingLocked(key2, value1)) { -// assertTrue(rc.present()); -// assertEquals(22, value2.getValue()); -// } try (ExternalMapQueryContext c = map.queryContext(key2)) { MapEntry entry = c.entry(); assertNotNull(entry); @@ -2312,18 +2288,18 @@ public void testListValue() throws IOException { try (ChronicleMap> map = newInstance(builder)) { map.put("1", Collections.emptyList()); - map.put("2", asList("two-A")); + map.put("2", Collections.singletonList("two-A")); List list1 = new ArrayList<>(); try (net.openhft.chronicle.core.io.Closeable c = map.acquireContext("1", list1)) { list1.add("one"); - assertEquals(asList("one"), list1); + assertEquals(Collections.singletonList("one"), list1); } List list2 = new ArrayList<>(); try (ExternalMapQueryContext, ?> c = map.queryContext("1")) { MapEntry> entry = c.entry(); assertNotNull(entry); - assertEquals(asList("one"), entry.value().getUsing(list2)); + assertEquals(Collections.singletonList("one"), entry.value().getUsing(list2)); } try (ExternalMapQueryContext, ?> c = map.queryContext("2")) { @@ -2358,18 +2334,18 @@ public void testSetValue() throws IOException { try (ChronicleMap> map = newInstance(builder)) { map.put("1", Collections.emptySet()); - map.put("2", new LinkedHashSet<>(asList("one"))); + map.put("2", new LinkedHashSet<>(Collections.singletonList("one"))); Set list1 = new LinkedHashSet<>(); try (net.openhft.chronicle.core.io.Closeable c = map.acquireContext("1", list1)) { list1.add("two"); - assertEquals(new LinkedHashSet<>(asList("two")), list1); + assertEquals(new LinkedHashSet<>(Collections.singletonList("two")), list1); } Set list2 = new LinkedHashSet<>(); try (ExternalMapQueryContext, ?> c = map.queryContext("1")) { MapEntry> entry = c.entry(); assertNotNull(entry); - assertEquals(new LinkedHashSet<>(asList("two")), entry.value().getUsing(list2)); + assertEquals(new LinkedHashSet<>(Collections.singletonList("two")), entry.value().getUsing(list2)); } try (net.openhft.chronicle.core.io.Closeable c = map.acquireContext("2", list1)) { @@ -2656,7 +2632,7 @@ public String toString() { private static class StringPrefixUnaryOperator implements BiFunction, Serializable { - private String prefix; + private final String prefix; StringPrefixUnaryOperator(final String prefix1) { prefix = prefix1; diff --git a/src/test/java/net/openhft/chronicle/map/ChronicleMapEqualsTest.java b/src/test/java/net/openhft/chronicle/map/ChronicleMapEqualsTest.java index 76efdd684..34b7af090 100644 --- a/src/test/java/net/openhft/chronicle/map/ChronicleMapEqualsTest.java +++ b/src/test/java/net/openhft/chronicle/map/ChronicleMapEqualsTest.java @@ -7,7 +7,7 @@ import java.util.HashMap; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertEquals; public class ChronicleMapEqualsTest { @@ -22,6 +22,6 @@ public void test() { HashMap refMap = new HashMap<>(); refMap.put("a", "b"); map.putAll(refMap); - assertTrue(map.equals(refMap)); + assertEquals(map, refMap); } } diff --git a/src/test/java/net/openhft/chronicle/map/ChronicleMapImportExportTest.java b/src/test/java/net/openhft/chronicle/map/ChronicleMapImportExportTest.java index 469139431..13580427d 100644 --- a/src/test/java/net/openhft/chronicle/map/ChronicleMapImportExportTest.java +++ b/src/test/java/net/openhft/chronicle/map/ChronicleMapImportExportTest.java @@ -15,8 +15,8 @@ import org.junit.Test; import java.io.File; -import java.io.FileOutputStream; import java.io.IOException; +import java.nio.file.Files; import java.util.HashMap; import java.util.Map; @@ -31,7 +31,7 @@ public class ChronicleMapImportExportTest { public static final String TMP = OS.getTarget(); @Test - public void test() throws IOException, InterruptedException { + public void test() throws IOException { File file = new File(TMP + "/chronicle-map-" + Time.uniqueId() + ".json"); file.deleteOnExit(); @@ -56,7 +56,7 @@ public void test() throws IOException, InterruptedException { } @Test - public void testWithMapValue() throws IOException, InterruptedException { + public void testWithMapValue() throws IOException { File file = new File(TMP + "/chronicle-map-" + Time.uniqueId() + ".json"); file.deleteOnExit(); @@ -85,7 +85,7 @@ public void testWithMapValue() throws IOException, InterruptedException { } @Test - public void testWithMapOfMapValue() throws IOException, InterruptedException { + public void testWithMapOfMapValue() throws IOException { File file = new File(TMP + "/chronicle-map-" + Time.uniqueId() + ".json"); file.deleteOnExit(); @@ -115,7 +115,7 @@ public void testWithMapOfMapValue() throws IOException, InterruptedException { } @Test - public void testWithIntegerAndDouble() throws IOException, InterruptedException { + public void testWithIntegerAndDouble() throws IOException { File file = new File(TMP + "/chronicle-map-" + Time.uniqueId() + ".json"); file.deleteOnExit(); @@ -138,7 +138,7 @@ public void testWithIntegerAndDouble() throws IOException, InterruptedException } @Test - public void testWithCharSeq() throws IOException, InterruptedException { + public void testWithCharSeq() throws IOException { File file = new File(TMP + "/chronicle-map-" + Time.uniqueId() + ".json"); file.deleteOnExit(); @@ -166,7 +166,7 @@ public void testWithCharSeq() throws IOException, InterruptedException { } @Test - public void testFromHashMap() throws IOException, InterruptedException { + public void testFromHashMap() throws IOException { File file = new File(TMP + "/chronicle-map-" + Time.uniqueId() + ".json"); System.out.println(file.getCanonicalFile()); @@ -181,7 +181,7 @@ public void testFromHashMap() throws IOException, InterruptedException { final XStream xstream = new XStream(new JettisonMappedXmlDriver()); xstream.setMode(XStream.NO_REFERENCES); - xstream.toXML(map, new FileOutputStream(file)); + xstream.toXML(map, Files.newOutputStream(file.toPath())); try (ChronicleMap expected = ChronicleMapBuilder .of(Integer.class, String.class) @@ -204,7 +204,7 @@ public void testFromHashMap() throws IOException, InterruptedException { } @Test - public void testWithLongValue() throws IOException, InterruptedException { + public void testWithLongValue() throws IOException { File file = new File(TMP + "/chronicle-map-" + Time.uniqueId() + ".json"); //file.deleteOnExit(); @@ -233,12 +233,12 @@ public void testWithLongValue() throws IOException, InterruptedException { Assert.assertEquals(expected, actual); } } finally { - // file.delete(); + file.delete(); } } @Test - public void testBondVOInterface() throws IOException, InterruptedException { + public void testBondVOInterface() throws IOException { File file = new File(TMP + "/chronicle-map-" + Time.uniqueId() + ".json"); file.deleteOnExit(); diff --git a/src/test/java/net/openhft/chronicle/map/ChronicleMapSanityCheckTest.java b/src/test/java/net/openhft/chronicle/map/ChronicleMapSanityCheckTest.java index d87bd739c..6beed2bbd 100644 --- a/src/test/java/net/openhft/chronicle/map/ChronicleMapSanityCheckTest.java +++ b/src/test/java/net/openhft/chronicle/map/ChronicleMapSanityCheckTest.java @@ -24,7 +24,7 @@ public class ChronicleMapSanityCheckTest { @Test - public void testSanity1() throws IOException, InterruptedException { + public void testSanity1() throws IOException { String tmp = OS.getTarget(); @@ -33,7 +33,7 @@ public void testSanity1() throws IOException, InterruptedException { File file = new File(pathname); System.out.println("Starting sanity test 1. Chronicle file :" + - file.getAbsolutePath().toString()); + file.getAbsolutePath()); ScheduledExecutorService producerExecutor = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors() - 1, @@ -43,7 +43,7 @@ public void testSanity1() throws IOException, InterruptedException { Executors.newSingleThreadScheduledExecutor( new NamedThreadFactory("consumer")); - int N = 1000; + int iterations = 1000; int producerPeriod = 100; TimeUnit producerTimeUnit = TimeUnit.MILLISECONDS; @@ -55,8 +55,8 @@ public void testSanity1() throws IOException, InterruptedException { try (ChronicleMap map = ChronicleMapBuilder.of(String.class, DummyValue.class) - .averageKey("" + N).averageValue(DummyValue.DUMMY_VALUE) - .entries(N) + .averageKey("" + iterations).averageValue(DummyValue.DUMMY_VALUE) + .entries(iterations) .createPersistedTo(file)) { map.clear(); @@ -67,7 +67,7 @@ public void testSanity1() throws IOException, InterruptedException { Random r = new Random(); System.out.println("Before PRODUCING size is " + map.size()); - for (int i = 0; i < N; i++) { + for (int i = 0; i < iterations; i++) { LockSupport.parkNanos(r.nextInt(5)); map.put(String.valueOf(i), DummyValue.DUMMY_VALUE); } diff --git a/src/test/java/net/openhft/chronicle/map/ChronicleMapTest.java b/src/test/java/net/openhft/chronicle/map/ChronicleMapTest.java index 5495fd887..50f81fc33 100644 --- a/src/test/java/net/openhft/chronicle/map/ChronicleMapTest.java +++ b/src/test/java/net/openhft/chronicle/map/ChronicleMapTest.java @@ -27,6 +27,7 @@ import static java.util.stream.Collectors.toSet; import static org.junit.Assert.*; + @org.junit.Ignore("flaky test see - https://teamcity.chronicle.software/repository/download/OpenHFT_ReleaseJob_ReleaseByArtifact/643179:id/ReleaseAutomation/projects/chronicle-map-runTests-1642011539698.log") @SuppressWarnings({"rawtypes", "unchecked", "ResultOfMethodCallIgnored", "try"}) public class ChronicleMapTest { @@ -96,8 +97,8 @@ public static IntValue nativeIntValue() { } static File getPersistenceFile() { - String TMP = OS.getTarget(); - File file = new File(TMP + "/chm-test" + Time.uniqueId() + count++); + String tmpDir = OS.getTarget(); + File file = new File(tmpDir + "/chm-test" + Time.uniqueId() + count++); file.deleteOnExit(); return file; } @@ -116,7 +117,7 @@ private static void printStatus() { } } - private ChronicleMap getViewTestMap(int noOfElements) throws IOException { + private ChronicleMap getViewTestMap(int noOfElements) { ChronicleMap map = ChronicleMapBuilder.of(Integer.class, CharSequence.class) .entries(noOfElements * 2 + 100) @@ -165,7 +166,7 @@ public void testRemoveWithKey() { assertEquals("one", result.toString()); assertFalse(map.containsKey("key1")); - assertEquals(null, map.get("key1")); + assertNull(map.get("key1")); assertEquals("two", map.get("key2").toString()); assertFalse(map.containsKey("key3")); @@ -293,7 +294,7 @@ public void testSize() { } @Test - public void testRemoveInteger() throws IOException { + public void testRemoveInteger() { int count = 300; try (final ChronicleMap map = ChronicleMapBuilder @@ -341,13 +342,13 @@ public void testRemoveWithKeyAndRemoveReturnsNull() { assertEquals("two", map.get("key2").toString()); final CharSequence result = map.remove("key1"); - assertEquals(null, result); + assertNull(result); assertEquals(1, map.size()); assertFalse(map.containsKey("key1")); - assertEquals(null, map.get("key1")); + assertNull(map.get("key1")); assertEquals("two", map.get("key2").toString()); assertFalse(map.containsKey("key3")); @@ -424,7 +425,7 @@ public void testReplaceWithKey() { assertEquals("newValue", map.get("key2").toString()); final CharSequence result3 = map.replace("rubbish", "newValue"); - assertEquals(null, result3); + assertNull(result3); assertFalse(map.containsKey("rubbish")); assertEquals(3, map.size()); @@ -449,7 +450,7 @@ public void testReplaceWithKeyAnd2Params() { final boolean result = map.replace("key1", "one", "newValue"); - assertEquals(true, result); + assertTrue(result); assertEquals("newValue", map.get("key1").toString()); assertEquals("two", map.get("key2").toString()); @@ -464,14 +465,14 @@ public void testReplaceWithKeyAnd2Params() { final boolean result2 = map.replace("key2", "two", "newValue2"); - assertEquals(true, result2); + assertTrue(result2); assertEquals("newValue2", map.get("key2").toString()); final boolean result3 = map.replace("newKey", "", "newValue"); - assertEquals(false, result3); + assertFalse(result3); final boolean result4 = map.replace("key2", "newValue2", "newValue2"); - assertEquals(true, result4); + assertTrue(result4); } } @@ -497,14 +498,14 @@ public void testReplaceWithKeyAnd2Params() { // TODO small GC on startup should be tidied up, [GC 9216K->1886K(31744K), 0.0036750 secs] // 10M users, updated 16 times. Throughput 33.0M ops/sec, VmPeak: 5373848 kB, VmRSS: 544252 kB // 50M users, updated 16 times. Throughput 31.2 M ops/sec, VmPeak: 9091804 kB, VmRSS: 3324732 kB - // 250M users, updated 16 times. Throughput 30.0 M ops/sec, VmPeak: 24807836 kB, VmRSS: 14329112 kB + // 250M users, updated 16 times. Throughput 30.0 M ops/sec, VmPeak: 24807836 kB, VmRSS: 14329112 kB // 1000M users, updated 16 times, Throughput 24.1 M ops/sec, VmPeak: 85312732 kB, VmRSS: 57165952 kB // 2500M users, updated 16 times, Throughput 23.5 M ops/sec, VmPeak: 189545308 kB, VmRSS: 126055868 kB // to ext4 // 10M users, updated 16 times. Throughput 28.4 M ops/sec, VmPeak: 5438652 kB, VmRSS: 544624 kB // 50M users, updated 16 times. Throughput 28.2 M ops/sec, VmPeak: 9091804 kB, VmRSS: 9091804 kB - // 250M users, updated 16 times. Throughput 26.1 M ops/sec, VmPeak: 24807836 kB, VmRSS: 24807836 kB + // 250M users, updated 16 times. Throughput 26.1 M ops/sec, VmPeak: 24807836 kB, VmRSS: 24807836 kB // 1000M users, updated 16 times, Throughput 1.3 M ops/sec, TODO FIX this @Test @@ -527,8 +528,8 @@ public void testRemoveWithKeyAndValue() { assertFalse(wasRemoved1); - assertEquals(null, map.get("key1").toString(), "one"); - assertEquals("two", map.get("key2").toString(), "two"); + assertEquals(null, "one", map.get("key1").toString()); + assertEquals("two", "two", map.get("key2").toString()); map.put("key1", "one"); @@ -599,8 +600,7 @@ public void testGetWithoutAcquireFirst() { } @Test - public void testAcquireAndGet() throws IOException, ClassNotFoundException, - IllegalAccessException, InstantiationException { + public void testAcquireAndGet() { int entries = 3/*00 * 1000*/; try (ChronicleMap map2 = ChronicleMapBuilder.of(CharSequence.class, LongValue.class) @@ -639,9 +639,9 @@ public void testAcquireAndGet() throws IOException, ClassNotFoundException, try (ChronicleMap map1 = ChronicleMapBuilder.of(CharSequence.class, LongValue.class) .entries((long) entries) -// .minSegments(1) + // .minSegments(1) .averageKeySize(10) -// .entryAndValueOffsetAlignment(8) + // .entryAndValueOffsetAlignment(8) .create()) { LongValue value1 = Values.newNativeReference(LongValue.class); LongValue value21 = Values.newNativeReference(LongValue.class); @@ -820,10 +820,8 @@ public void testLargerEntries() { @Test @Ignore("Performance test") - public void testAcquirePerf256() - throws IOException, ClassNotFoundException, IllegalAccessException, - InstantiationException, InterruptedException, ExecutionException { -// int runs = Integer.getInteger("runs", 10); + public void testAcquirePerf256() { + // int runs = Integer.getInteger("runs", 10); int procs = 1; // Runtime.getRuntime().availableProcessors(); int threads = procs * 3; for (int runs : new int[]{1, /*10, 250, 500, 1000, 2500*/}) { @@ -843,8 +841,8 @@ public void testAcquirePerf256() .averageKeySize(14) .averageValueSize(value0.length() + 4); -// File tmpFile = File.createTempFile("testAcquirePerf", ".deleteme"); -// tmpFile.deleteOnExit(); + // File tmpFile = File.createTempFile("testAcquirePerf", ".deleteme"); + // tmpFile.deleteOnExit(); //createPersistedTo(tmpFile); try (final ChronicleMap map = builder.create()) { @@ -853,16 +851,15 @@ public void testAcquirePerf256() for (int j = 0; j < count; j++) { long start = System.currentTimeMillis(); for (int i = 0; i < threads; i++) { - final int t = i; - Random rand = new Random(t); + Random rand = new Random(i); StringBuilder key = new StringBuilder(); StringBuilder value = new StringBuilder(); long next = 50 * 1000 * 1000; // use a factor to give up to 10 digit numbers. int factor = Math.max(1, (int) ((10 * 1000 * 1000 * 1000L - 1) / entries)); - for (long k = t; k < entries; k++) { + for (long k = i; k < entries; k++) { key.setLength(0); key.append("us:"); key.append(k * factor); @@ -903,7 +900,7 @@ else if (value.length() > value0.length()) public void testAcquirePerf() throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException, InterruptedException, ExecutionException { -// int runs = Integer.getInteger("runs", 10); + // int runs = Integer.getInteger("runs", 10); int procs = 1; // Runtime.getRuntime().availableProcessors(); int threads = procs * 3; ExecutorService es = Executors.newFixedThreadPool(procs, new NamedThreadFactory("test")); @@ -924,8 +921,8 @@ public void testAcquirePerf() .averageKeySize(14) .averageValueSize(value0.length() + 4); -// File tmpFile = File.createTempFile("testAcquirePerf", ".deleteme"); -// tmpFile.deleteOnExit(); + // File tmpFile = File.createTempFile("testAcquirePerf", ".deleteme"); + // tmpFile.deleteOnExit(); try (final ChronicleMap map = builder.create()) { @@ -994,7 +991,7 @@ else if (value.length() > value0.length()) @Ignore("Performance test") public void testAcquireLockedPerf() throws IOException, InterruptedException, ExecutionException { -// int runs = Integer.getInteger("runs", 10); + // int runs = Integer.getInteger("runs", 10); int procs = Runtime.getRuntime().availableProcessors(); if (procs > 8) procs--; int threads = procs * 3; @@ -1092,13 +1089,13 @@ public void run() { public void testAcquireLockedLLPerf() throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException, InterruptedException, ExecutionException { -// int runs = Integer.getInteger("runs", 10); + // int runs = Integer.getInteger("runs", 10); int procs = Runtime.getRuntime().availableProcessors(); int threads = procs * 3; // runs > 100 ? procs / 2 : procs; ExecutorService es = Executors.newFixedThreadPool(procs, new NamedThreadFactory("test")); for (int runs : new int[]{10, 50, 100, 250, 500, 1000, 2500}) { -// JAVA 8 produces more garbage than previous versions for internal work. -// System.gc(); + // JAVA 8 produces more garbage than previous versions for internal work. + // System.gc(); final long entries = runs * 1000 * 1000L; ChronicleMapBuilder builder = ChronicleMapBuilder .of(LongValue.class, LongValue.class) @@ -1173,7 +1170,7 @@ public void testCHMAcquirePerf() throws IOException, ClassNotFoundException, Ill final int independence = Math.min(procs, runs > 500 ? 8 : 4); for (int j = 0; j < count; j++) { final ConcurrentMap map = new ConcurrentHashMap((int) (entries * 5 / 4), 1.0f, 1024); - long start = System.currentTimeMillis(); + final long start = System.currentTimeMillis(); ExecutorService es = Executors.newFixedThreadPool(procs, new NamedThreadFactory("test")); for (int i = 0; i < threads; i++) { final int t = i; @@ -1220,8 +1217,7 @@ private CharSequence getUserCharSequence(int i) { } @Test - public void testPutAndRemove() throws IOException, ClassNotFoundException, - IllegalAccessException, InstantiationException { + public void testPutAndRemove() { int entries = 100 * 1000; try (ChronicleMap map = @@ -1241,7 +1237,7 @@ public void testPutAndRemove() throws IOException, ClassNotFoundException, key.append("user:").append(i); value.setLength(0); value.append("value:").append(i); -// System.out.println(key); + // System.out.println(key); assertNull(map.getUsing(key, value)); assertNull(map.put(key, value)); assertNotNull(map.getUsing(key, value2)); @@ -1255,10 +1251,10 @@ public void testPutAndRemove() throws IOException, ClassNotFoundException, @Test public void mapRemoveReflectedInViews() throws IOException { - try (ChronicleMap map = getViewTestMap(3);) { - Set> entrySet = map.entrySet(); - Set keySet = map.keySet(); - Collection values = map.values(); + try (ChronicleMap map = getViewTestMap(3)) { + final Set> entrySet = map.entrySet(); + final Set keySet = map.keySet(); + final Collection values = map.values(); map.remove(2); assertMap(map, new int[]{1, 3}, new CharSequence[]{"1", "3"}); @@ -1274,9 +1270,9 @@ public void mapRemoveReflectedInViews() throws IOException { @Test public void mapPutReflectedInViews() throws IOException { try (ChronicleMap map = getViewTestMap(3)) { - Set> entrySet = map.entrySet(); - Set keySet = map.keySet(); - Collection values = map.values(); + final Set> entrySet = map.entrySet(); + final Set keySet = map.keySet(); + final Collection values = map.values(); map.put(4, "4"); assertMap(map, new int[]{4, 2, 3, 1}, new CharSequence[]{"4", "2", "3", "1"}); @@ -1292,9 +1288,9 @@ public void mapPutReflectedInViews() throws IOException { @Test public void entrySetRemoveReflectedInMapAndOtherViews() throws IOException { try (ChronicleMap map = getViewTestMap(3)) { - Set> entrySet = map.entrySet(); - Set keySet = map.keySet(); - Collection values = map.values(); + final Set> entrySet = map.entrySet(); + final Set keySet = map.keySet(); + final Collection values = map.values(); entrySet.remove(new AbstractMap.SimpleEntry(2, "2")); assertMap(map, new int[]{1, 3}, new CharSequence[]{"1", "3"}); @@ -1307,9 +1303,9 @@ public void entrySetRemoveReflectedInMapAndOtherViews() throws IOException { @Test public void keySetRemoveReflectedInMapAndOtherViews() throws IOException { try (ChronicleMap map = getViewTestMap(3)) { - Set> entrySet = map.entrySet(); - Set keySet = map.keySet(); - Collection values = map.values(); + final Set> entrySet = map.entrySet(); + final Set keySet = map.keySet(); + final Collection values = map.values(); keySet.remove(2); assertMap(map, new int[]{1, 3}, new CharSequence[]{"1", "3"}); @@ -1324,9 +1320,9 @@ public void keySetRemoveReflectedInMapAndOtherViews() throws IOException { @Test public void valuesRemoveReflectedInMap() throws IOException { try (ChronicleMap map = getViewTestMap(3)) { - Set> entrySet = map.entrySet(); - Set keySet = map.keySet(); - Collection values = map.values(); + final Set> entrySet = map.entrySet(); + final Set keySet = map.keySet(); + final Collection values = map.values(); values.removeIf("2"::contentEquals); assertMap(map, new int[]{1, 3}, new CharSequence[]{"1", "3"}); @@ -1340,10 +1336,10 @@ public void valuesRemoveReflectedInMap() throws IOException { @Test public void entrySetIteratorRemoveReflectedInMapAndOtherViews() throws IOException { try (ChronicleMap map = getViewTestMap(3)) { - Map refMap = new HashMap<>(map); - Set> entrySet = map.entrySet(); - Set keySet = map.keySet(); - Collection values = map.values(); + final Map refMap = new HashMap<>(map); + final Set> entrySet = map.entrySet(); + final Set keySet = map.keySet(); + final Collection values = map.values(); Iterator> entryIterator = entrySet.iterator(); entryIterator.next(); @@ -1361,10 +1357,10 @@ public void entrySetIteratorRemoveReflectedInMapAndOtherViews() throws IOExcepti @Test public void keySetIteratorRemoveReflectedInMapAndOtherViews() throws IOException { try (ChronicleMap map = getViewTestMap(3)) { - Map refMap = new HashMap<>(map); - Set> entrySet = map.entrySet(); - Set keySet = map.keySet(); - Collection values = map.values(); + final Map refMap = new HashMap<>(map); + final Set> entrySet = map.entrySet(); + final Set keySet = map.keySet(); + final Collection values = map.values(); Iterator keyIterator = keySet.iterator(); keyIterator.next(); @@ -1383,12 +1379,12 @@ public void keySetIteratorRemoveReflectedInMapAndOtherViews() throws IOException @Test public void valuesIteratorRemoveReflectedInMapAndOtherViews() throws IOException { try (ChronicleMap map = getViewTestMap(3)) { - HashBiMap refMap = HashBiMap.create(); + final HashBiMap refMap = HashBiMap.create(); map.forEach((k, v) -> refMap.put(k, v.toString())); - Set> entrySet = map.entrySet(); - Set keySet = map.keySet(); - Collection values = map.values(); + final Set> entrySet = map.entrySet(); + final Set keySet = map.keySet(); + final Collection values = map.values(); Iterator valueIterator = values.iterator(); valueIterator.next(); @@ -1410,9 +1406,9 @@ public void valuesIteratorRemoveReflectedInMapAndOtherViews() throws IOException @Test public void entrySetRemoveAllReflectedInMapAndOtherViews() throws IOException { try (ChronicleMap map = getViewTestMap(3)) { - Set> entrySet = map.entrySet(); - Set keySet = map.keySet(); - Collection values = map.values(); + final Set> entrySet = map.entrySet(); + final Set keySet = map.keySet(); + final Collection values = map.values(); entrySet.removeAll( Arrays.asList( @@ -1431,9 +1427,9 @@ public void entrySetRemoveAllReflectedInMapAndOtherViews() throws IOException { @Test public void keySetRemoveAllReflectedInMapAndOtherViews() throws IOException { try (ChronicleMap map = getViewTestMap(3)) { - Set> entrySet = map.entrySet(); - Set keySet = map.keySet(); - Collection values = map.values(); + final Set> entrySet = map.entrySet(); + final Set keySet = map.keySet(); + final Collection values = map.values(); keySet.removeAll(Arrays.asList(1, 2)); assertMap(map, new int[]{3}, new CharSequence[]{"3"}); @@ -1447,9 +1443,9 @@ public void keySetRemoveAllReflectedInMapAndOtherViews() throws IOException { @Test public void valuesRemoveAllReflectedInMapAndOtherViews() throws IOException { try (ChronicleMap map = getViewTestMap(3)) { - Set> entrySet = map.entrySet(); - Set keySet = map.keySet(); - Collection values = map.values(); + final Set> entrySet = map.entrySet(); + final Set keySet = map.keySet(); + final Collection values = map.values(); values.removeIf(e -> "1".contentEquals(e) || "2".contentEquals(e)); assertMap(map, new int[]{3}, new CharSequence[]{"3"}); @@ -1463,9 +1459,9 @@ public void valuesRemoveAllReflectedInMapAndOtherViews() throws IOException { @Test public void entrySetRetainAllReflectedInMapAndOtherViews() throws IOException { try (ChronicleMap map = getViewTestMap(3)) { - Set> entrySet = map.entrySet(); - Set keySet = map.keySet(); - Collection values = map.values(); + final Set> entrySet = map.entrySet(); + final Set keySet = map.keySet(); + final Collection values = map.values(); entrySet.removeIf(e -> !(e.getKey().equals(1) && "1".contentEquals(e.getValue())) && @@ -1481,9 +1477,9 @@ public void entrySetRetainAllReflectedInMapAndOtherViews() throws IOException { @Test public void keySetRetainAllReflectedInMapAndOtherViews() throws IOException { try (ChronicleMap map = getViewTestMap(3)) { - Set> entrySet = map.entrySet(); - Set keySet = map.keySet(); - Collection values = map.values(); + final Set> entrySet = map.entrySet(); + final Set keySet = map.keySet(); + final Collection values = map.values(); keySet.retainAll(Arrays.asList(1, 2)); assertMap(map, new int[]{2, 1}, new CharSequence[]{"2", "1"}); @@ -1497,9 +1493,9 @@ public void keySetRetainAllReflectedInMapAndOtherViews() throws IOException { @Test public void valuesRetainAllReflectedInMapAndOtherViews() throws IOException { try (ChronicleMap map = getViewTestMap(3)) { - Set> entrySet = map.entrySet(); - Set keySet = map.keySet(); - Collection values = map.values(); + final Set> entrySet = map.entrySet(); + final Set keySet = map.keySet(); + final Collection values = map.values(); values.removeIf(v -> !"1".contentEquals(v) && !"2".contentEquals(v)); assertMap(map, new int[]{2, 1}, new CharSequence[]{"2", "1"}); @@ -1513,9 +1509,9 @@ public void valuesRetainAllReflectedInMapAndOtherViews() throws IOException { @Test public void entrySetClearReflectedInMapAndOtherViews() throws IOException { try (ChronicleMap map = getViewTestMap(3)) { - Set> entrySet = map.entrySet(); - Set keySet = map.keySet(); - Collection values = map.values(); + final Set> entrySet = map.entrySet(); + final Set keySet = map.keySet(); + final Collection values = map.values(); entrySet.clear(); org.junit.Assert.assertTrue(map.isEmpty()); @@ -1529,9 +1525,9 @@ public void entrySetClearReflectedInMapAndOtherViews() throws IOException { @Test public void keySetClearReflectedInMapAndOtherViews() throws IOException { try (ChronicleMap map = getViewTestMap(3)) { - Set> entrySet = map.entrySet(); - Set keySet = map.keySet(); - Collection values = map.values(); + final Set> entrySet = map.entrySet(); + final Set keySet = map.keySet(); + final Collection values = map.values(); keySet.clear(); org.junit.Assert.assertTrue(map.isEmpty()); @@ -1545,9 +1541,9 @@ public void keySetClearReflectedInMapAndOtherViews() throws IOException { @Test public void valuesClearReflectedInMapAndOtherViews() throws IOException { try (ChronicleMap map = getViewTestMap(3)) { - Set> entrySet = map.entrySet(); - Set keySet = map.keySet(); - Collection values = map.values(); + final Set> entrySet = map.entrySet(); + final Set keySet = map.keySet(); + final Collection values = map.values(); values.clear(); org.junit.Assert.assertTrue(map.isEmpty()); @@ -1628,9 +1624,9 @@ public void entrySetValueReflectedInMapAndOtherViews() throws IOException { try (ChronicleMap map = getViewTestMap(0)) { map.put(1, "A"); - Set> entrySet = map.entrySet(); - Set keySet = map.keySet(); - Collection values = map.values(); + final Set> entrySet = map.entrySet(); + final Set keySet = map.keySet(); + final Collection values = map.values(); assertMap(map, new int[]{1}, new CharSequence[]{"A"}); assertEntrySet(entrySet, new int[]{1}, new CharSequence[]{"A"}); @@ -1650,7 +1646,7 @@ public void entrySetValueReflectedInMapAndOtherViews() throws IOException { } @Test - public void equalsTest() throws IOException { + public void equalsTest() { try (final ChronicleMap map1 = ChronicleMap.of(Integer.class, String.class) .averageValue("one").entries(2).create()) { @@ -1669,7 +1665,7 @@ public void equalsTest() throws IOException { } @Test - public void testPutLongValue() throws IOException { + public void testPutLongValue() { final ChronicleMapBuilder builder = ChronicleMapBuilder .of(CharSequence.class, LongValue.class) .entries(1000) @@ -1690,7 +1686,7 @@ public void testPutLongValue() throws IOException { } @Test - public void testOffheapAcquireUsingLocked() throws IOException { + public void testOffheapAcquireUsingLocked() { ChronicleMapBuilder builder = ChronicleMapBuilder .of(CharSequence.class, LongValue.class) .entries(1000) @@ -1758,17 +1754,17 @@ public void testAcquireUsingLockedWithString() { // Apparently, Java 17 does a better job internalizing/de-duplicating strings so, we have to explicitly create // a new empty string - final String newEmptyString = new String(""); + final String newEmptyString = ""; // this will add the entry try (net.openhft.chronicle.core.io.Closeable c = map.acquireContext("one", newEmptyString)) { - // do nothing + assertNotNull(c); } } } @Test - public void testOnheapAcquireUsingLockedStringBuilder() throws IOException { + public void testOnheapAcquireUsingLockedStringBuilder() { try (final ChronicleMap map = ChronicleMapBuilder .of(CharSequence.class, CharSequence.class) diff --git a/src/test/java/net/openhft/chronicle/map/ConstantSizeBySampleTest.java b/src/test/java/net/openhft/chronicle/map/ConstantSizeBySampleTest.java index 0a07037f9..0720bd03a 100644 --- a/src/test/java/net/openhft/chronicle/map/ConstantSizeBySampleTest.java +++ b/src/test/java/net/openhft/chronicle/map/ConstantSizeBySampleTest.java @@ -39,7 +39,7 @@ public void testConstantKeys() { } @Test - public void testUnexpectedlyLongConstantByteArrayValues() throws IOException { + public void testUnexpectedlyLongConstantByteArrayValues() { try (ChronicleMap map = ChronicleMapBuilder.of(Long.class, byte[].class) .constantValueSizeBySample(new byte[512 * 1024]) .entries(100) @@ -49,12 +49,12 @@ public void testUnexpectedlyLongConstantByteArrayValues() throws IOException { value[42] = 1; map.put(1L, value); - Assert.assertTrue(Arrays.equals(map.get(1L), value)); + Assert.assertArrayEquals(map.get(1L), value); } } @Test - public void testUnexpectedlyLongConstantExternalizableValues() throws IOException { + public void testUnexpectedlyLongConstantExternalizableValues() { try (ChronicleMap map = ChronicleMapBuilder.of(Long.class, ExternalizableData.class) .valueReaderAndDataAccess(new ExternalizableDataReader(), @@ -71,7 +71,7 @@ public void testUnexpectedlyLongConstantExternalizableValues() throws IOExceptio } @Test - public void testUnexpectedlyLongConstantSerializableValues() throws IOException { + public void testUnexpectedlyLongConstantSerializableValues() { try (ChronicleMap map = ChronicleMapBuilder.of(Long.class, SerializableData.class) .constantValueSizeBySample(new SerializableData()) @@ -109,13 +109,13 @@ public void writeExternal(ObjectOutput out) throws IOException { } @Override - public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { + public void readExternal(ObjectInput in) throws IOException { in.read(data = new byte[512 * 1024]); } } static final class SerializableData implements Serializable { - byte[] data = new byte[512 * 1024]; + final byte[] data = new byte[512 * 1024]; @Override public boolean equals(Object obj) { diff --git a/src/test/java/net/openhft/chronicle/map/DataKeyValueTest.java b/src/test/java/net/openhft/chronicle/map/DataKeyValueTest.java index 8b5546cde..61a72372e 100644 --- a/src/test/java/net/openhft/chronicle/map/DataKeyValueTest.java +++ b/src/test/java/net/openhft/chronicle/map/DataKeyValueTest.java @@ -19,7 +19,7 @@ public void dataKeyValueTest() { .entries(1000).create(); IntValue heapKey = Values.newHeapInstance(IntValue.class); LongValue heapValue = Values.newHeapInstance(LongValue.class); - LongValue directValue = Values.newNativeReference(LongValue.class); + final LongValue directValue = Values.newNativeReference(LongValue.class); heapKey.setValue(1); heapValue.setValue(1); diff --git a/src/test/java/net/openhft/chronicle/map/DatasetTrackerIssue61Test.java b/src/test/java/net/openhft/chronicle/map/DatasetTrackerIssue61Test.java index fd62d2ee0..1ad8a9436 100644 --- a/src/test/java/net/openhft/chronicle/map/DatasetTrackerIssue61Test.java +++ b/src/test/java/net/openhft/chronicle/map/DatasetTrackerIssue61Test.java @@ -55,7 +55,7 @@ public void writeExternal(ObjectOutput out) throws IOException { } @Override - public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { + public void readExternal(ObjectInput in) throws IOException { value = in.readUTF(); } } diff --git a/src/test/java/net/openhft/chronicle/map/DefaultValueTest.java b/src/test/java/net/openhft/chronicle/map/DefaultValueTest.java index 21f11387a..8e82ee78d 100644 --- a/src/test/java/net/openhft/chronicle/map/DefaultValueTest.java +++ b/src/test/java/net/openhft/chronicle/map/DefaultValueTest.java @@ -46,10 +46,7 @@ public void test1() { private static class SimpleDefaultValueProvider extends SelfDescribingMarshallable implements DefaultValueProvider { - private final V defaultValue; - public SimpleDefaultValueProvider(V defaultValue) { - this.defaultValue = defaultValue; } @Override @@ -81,7 +78,7 @@ public void writeMarshallable(BytesOut bytes) throws IllegalStateException, B } @Test - public void test() throws IllegalAccessException, InstantiationException, IOException { + public void test() throws IOException { File file = Builder.getPersistenceFile(); try { diff --git a/src/test/java/net/openhft/chronicle/map/DeflatorStringMarshaller.java b/src/test/java/net/openhft/chronicle/map/DeflatorStringMarshaller.java index 7086b1a19..c56c47cb3 100644 --- a/src/test/java/net/openhft/chronicle/map/DeflatorStringMarshaller.java +++ b/src/test/java/net/openhft/chronicle/map/DeflatorStringMarshaller.java @@ -111,7 +111,7 @@ public DeflatorStringMarshaller readResolve() { return INSTANCE; } - private static abstract class StringFactory { + private abstract static class StringFactory { abstract String fromChars(char[] chars) throws Exception; } diff --git a/src/test/java/net/openhft/chronicle/map/DemoChronicleMapTest.java b/src/test/java/net/openhft/chronicle/map/DemoChronicleMapTest.java index a5857a170..cc23ff489 100644 --- a/src/test/java/net/openhft/chronicle/map/DemoChronicleMapTest.java +++ b/src/test/java/net/openhft/chronicle/map/DemoChronicleMapTest.java @@ -17,16 +17,16 @@ import static org.junit.Assert.assertNotNull; interface DemoOrderVOInterface { - public CharSequence getSymbol(); -// public StringBuilder getUsingSymbol(StringBuilder sb); + CharSequence getSymbol(); + // public StringBuilder getUsingSymbol(StringBuilder sb); - public void setSymbol(@MaxUtf8Length(20) CharSequence symbol); + void setSymbol(@MaxUtf8Length(20) CharSequence symbol); - public double addAtomicOrderQty(double toAdd); + double addAtomicOrderQty(double toAdd); - public double getOrderQty(); + double getOrderQty(); - public void setOrderQty(double orderQty); + void setOrderQty(double orderQty); } @@ -67,7 +67,7 @@ public void testMap() throws IOException { IntValue k = entry.getKey(); DemoOrderVOInterface v = entry.getValue(); -// System.out.println(String.format("Key %d %s", k.getValue(), v == null ? "" : v.getSymbol())); + // System.out.println(String.format("Key %d %s", k.getValue(), v == null ? "" : v.getSymbol())); assertNotNull(v); } } @@ -104,18 +104,18 @@ public void testMapLocked() throws IOException { } // TODO suspicious -- getUsing `value2`, working with `value` then -// try (ReadContext rc = map.getUsingLocked(key, value2)) { -// assertTrue(rc.present()); -// assertEquals("IBM-" + i, value.getSymbol()); -// assertEquals(1000, value.getOrderQty(), 0.0); -// } + // try (ReadContext rc = map.getUsingLocked(key, value2)) { + // assertTrue(rc.present()); + // assertEquals("IBM-" + i, value.getSymbol()); + // assertEquals(1000, value.getOrderQty(), 0.0); + // } } for (Map.Entry entry : map.entrySet()) { IntValue k = entry.getKey(); DemoOrderVOInterface v = entry.getValue(); -// System.out.println(String.format("Key %d %s", k.getValue(), v == null ? "" : v.getSymbol())); + // System.out.println(String.format("Key %d %s", k.getValue(), v == null ? "" : v.getSymbol())); assertNotNull(v); } } @@ -124,11 +124,11 @@ public void testMapLocked() throws IOException { @Test(expected = IllegalArgumentException.class) public void testNegativeIllegalAlignment() { - ChronicleMapBuilder.of(IntValue.class, DemoOrderVOInterface.class).entryAndValueOffsetAlignment(-1); + ChronicleMapBuilder.of(IntValue.class, DemoOrderVOInterface.class).entryAndValueOffsetAlignment(-1); } @Test(expected = IllegalArgumentException.class) public void testNotPowerOfTwoIllegalAlignment() { - ChronicleMapBuilder.of(IntValue.class, DemoOrderVOInterface.class).entryAndValueOffsetAlignment(13); + ChronicleMapBuilder.of(IntValue.class, DemoOrderVOInterface.class).entryAndValueOffsetAlignment(13); } } diff --git a/src/test/java/net/openhft/chronicle/map/ExitHookTest.java b/src/test/java/net/openhft/chronicle/map/ExitHookTest.java index cd6c470ed..416f655dd 100644 --- a/src/test/java/net/openhft/chronicle/map/ExitHookTest.java +++ b/src/test/java/net/openhft/chronicle/map/ExitHookTest.java @@ -36,7 +36,7 @@ public class ExitHookTest { private static AtomicReference> mapReference; @Rule - public TemporaryFolder folder = new TemporaryFolder(); + public final TemporaryFolder folder = new TemporaryFolder(); public static void main(String[] args) throws IOException, InterruptedException { @@ -232,7 +232,7 @@ private void interruptProcess(long pidOfProcess) throws IOException { Runtime.getRuntime().exec("kill -SIGINT " + pidOfProcess); } - private Process startOtherProcess(File mapFile, File lockingFile, File outputFile, boolean skipCloseOnExitHook) throws IOException { + private Process startOtherProcess(File mapFile, File lockingFile, File outputFile, boolean skipCloseOnExitHook) { return JavaProcessBuilder.create(ExitHookTest.class) //.inheritingIO() .withProgramArguments(mapFile.getAbsolutePath(), diff --git a/src/test/java/net/openhft/chronicle/map/FileLockUtilTest.java b/src/test/java/net/openhft/chronicle/map/FileLockUtilTest.java index 2fb7941a6..e688cec9f 100644 --- a/src/test/java/net/openhft/chronicle/map/FileLockUtilTest.java +++ b/src/test/java/net/openhft/chronicle/map/FileLockUtilTest.java @@ -21,7 +21,6 @@ public class FileLockUtilTest { private File canonicalFile; - private RandomAccessFile raf; private FileChannel fileChannel; @Before @@ -29,7 +28,7 @@ public void setUp() throws IOException { canonicalFile = new File("file.lock").getCanonicalFile(); canonicalFile.delete(); canonicalFile.createNewFile(); - raf = CanonicalRandomAccessFiles.acquire(canonicalFile); + RandomAccessFile raf = CanonicalRandomAccessFiles.acquire(canonicalFile); fileChannel = raf.getChannel(); } @@ -64,7 +63,8 @@ public void testTryExclusiveButWasShared() { try { CanonicalRandomAccessFiles.acquireExclusiveFileLock(canonicalFile, fileChannel); fail(); - } catch (ChronicleFileLockException ignore) { + } catch (ChronicleFileLockException e) { + assertNotNull(e); } CanonicalRandomAccessFiles.releaseSharedFileLock(canonicalFile); } @@ -77,7 +77,8 @@ public void testTrySharedButWasExclusive() { try { CanonicalRandomAccessFiles.acquireSharedFileLock(canonicalFile, fileChannel); fail(); - } catch (ChronicleFileLockException ignore) { + } catch (ChronicleFileLockException e) { + assertNotNull(e); } CanonicalRandomAccessFiles.releaseExclusiveFileLock(canonicalFile); } @@ -114,6 +115,7 @@ public void testRunExclusivelyButUsed() { fail(); } catch (ChronicleFileLockException e) { CanonicalRandomAccessFiles.releaseSharedFileLock(canonicalFile); + assertNotNull(e); } } } diff --git a/src/test/java/net/openhft/chronicle/map/GuavaTest.java b/src/test/java/net/openhft/chronicle/map/GuavaTest.java index 0b3aa3c4e..9ddf47a55 100644 --- a/src/test/java/net/openhft/chronicle/map/GuavaTest.java +++ b/src/test/java/net/openhft/chronicle/map/GuavaTest.java @@ -50,7 +50,7 @@ private static void configureSuite(MapTestSuiteBuilder suite) { .withFeatures(RESTRICTS_KEYS, RESTRICTS_VALUES); } - static abstract class TestGenerator + abstract static class TestGenerator implements TestMapGenerator { abstract Map newMap(); @@ -97,7 +97,7 @@ public Iterable> order( } static class CHMTestGenerator extends TestGenerator { - ChronicleMapBuilder builder = + final ChronicleMapBuilder builder = ChronicleMapBuilder.of(String.class, String.class) .entries(100) .averageKeySize(10).averageValueSize(10) diff --git a/src/test/java/net/openhft/chronicle/map/HugeSparseMapTest.java b/src/test/java/net/openhft/chronicle/map/HugeSparseMapTest.java index 0c24cd10d..f20303682 100644 --- a/src/test/java/net/openhft/chronicle/map/HugeSparseMapTest.java +++ b/src/test/java/net/openhft/chronicle/map/HugeSparseMapTest.java @@ -26,10 +26,9 @@ private static ChronicleMap createMap(boolean sparse builder.entries(3_000_000_000L).averageValueSize(16); // 216 GB else builder.entries(10_000_000_000L).averageValueSize(640); // 16 TB -// .entries(3_000_000_000L).averageValueSize(200) // 2 TB + // .entries(3_000_000_000L).averageValueSize(200) // 2 TB builder.sparseFile(sparseFile); // ~16 TB. - ChronicleMap map = builder.createPersistedTo(file); - return map; + return builder.createPersistedTo(file); } catch (Throwable t) { file.delete(); throw t; diff --git a/src/test/java/net/openhft/chronicle/map/IntValueMapTest.java b/src/test/java/net/openhft/chronicle/map/IntValueMapTest.java index ff4aaee9f..aac7a8901 100644 --- a/src/test/java/net/openhft/chronicle/map/IntValueMapTest.java +++ b/src/test/java/net/openhft/chronicle/map/IntValueMapTest.java @@ -9,8 +9,6 @@ import net.openhft.chronicle.values.Values; import org.junit.Test; -import java.io.IOException; - import static org.junit.Assert.assertEquals; /** @@ -19,7 +17,7 @@ public class IntValueMapTest { @Test - public void test() throws IOException { + public void test() { try (final ChronicleMap map = ChronicleMapBuilder .of(IntValue.class, CharSequence.class) diff --git a/src/test/java/net/openhft/chronicle/map/Issue125Test.java b/src/test/java/net/openhft/chronicle/map/Issue125Test.java index 6edbd5020..701062315 100644 --- a/src/test/java/net/openhft/chronicle/map/Issue125Test.java +++ b/src/test/java/net/openhft/chronicle/map/Issue125Test.java @@ -19,7 +19,7 @@ public void test() throws IOException { final File cacheRoot = new File(OS.getTarget() + "/test-" + Time.uniqueId() + ".cm3"); ChronicleMapBuilder shaToNodeBuilder = ChronicleMapBuilder.of(byte[].class, byte[].class) -// .name("bytes-to-bytes") + // .name("bytes-to-bytes") .entries(1000000). averageKeySize(20). averageValueSize(30); diff --git a/src/test/java/net/openhft/chronicle/map/Issue229Test.java b/src/test/java/net/openhft/chronicle/map/Issue229Test.java index c0c08df9c..c9d5b3b77 100644 --- a/src/test/java/net/openhft/chronicle/map/Issue229Test.java +++ b/src/test/java/net/openhft/chronicle/map/Issue229Test.java @@ -39,7 +39,7 @@ public void assureExclusiveAccess() throws IOException { .createPersistedTo(mapFile)) { assertNotNull(readMap); -// It shall not be possible to recover since the + // It shall not be possible to recover since the // file is open by the readMap try (ChronicleMap recoverMap = ChronicleMap .of(Long.class, Long.class) diff --git a/src/test/java/net/openhft/chronicle/map/Issue354bTest.java b/src/test/java/net/openhft/chronicle/map/Issue354bTest.java index 56eb3eb19..259243fba 100644 --- a/src/test/java/net/openhft/chronicle/map/Issue354bTest.java +++ b/src/test/java/net/openhft/chronicle/map/Issue354bTest.java @@ -16,7 +16,7 @@ public class Issue354bTest { @Rule - public TemporaryFolder testFolder = new TemporaryFolder(); + public final TemporaryFolder testFolder = new TemporaryFolder(); @Test public void build_toFile() throws IOException { diff --git a/src/test/java/net/openhft/chronicle/map/Issue42Test.java b/src/test/java/net/openhft/chronicle/map/Issue42Test.java index 8edaa976d..02ebe69fa 100644 --- a/src/test/java/net/openhft/chronicle/map/Issue42Test.java +++ b/src/test/java/net/openhft/chronicle/map/Issue42Test.java @@ -7,12 +7,10 @@ import org.junit.Assert; import org.junit.Test; -import java.io.IOException; - public class Issue42Test { @Test - public void crashJVMWindowsTest() throws IOException { + public void crashJVMWindowsTest() { if (!OS.isWindows()) return; diff --git a/src/test/java/net/openhft/chronicle/map/Issue43Test.java b/src/test/java/net/openhft/chronicle/map/Issue43Test.java index 02550267c..ac4322cde 100644 --- a/src/test/java/net/openhft/chronicle/map/Issue43Test.java +++ b/src/test/java/net/openhft/chronicle/map/Issue43Test.java @@ -11,25 +11,25 @@ import org.jetbrains.annotations.NotNull; import org.junit.Test; +import java.io.IOException; + +import static org.junit.Assert.assertNotNull; + public class Issue43Test { - public static void main(String[] args) { + public static void main(String[] args) throws IOException { new Issue43Test().testIssue43(); } @Test - public void testIssue43() { - try { - ChronicleMap map = ChronicleMapBuilder - .of(Long.class, ValueWrapper.class) - .entries(512) - .valueMarshaller(ArrayMarshaller.INSTANCE) - .constantValueSizeBySample(new ValueWrapper(new double[128])) - .createPersistedTo(Builder.getPersistenceFile()); - //System.out.println("Created the monkey map ValueWrapper 128"); - } catch (Throwable ex) { - System.out.println(ex); - } + public void testIssue43() throws IOException { + ChronicleMap map = ChronicleMapBuilder + .of(Long.class, ValueWrapper.class) + .entries(512) + .valueMarshaller(ArrayMarshaller.INSTANCE) + .constantValueSizeBySample(new ValueWrapper(new double[128])) + .createPersistedTo(Builder.getPersistenceFile()); + assertNotNull(map); } private static class ValueWrapper { diff --git a/src/test/java/net/openhft/chronicle/map/Issue58.java b/src/test/java/net/openhft/chronicle/map/Issue58.java index f45975133..699daede2 100644 --- a/src/test/java/net/openhft/chronicle/map/Issue58.java +++ b/src/test/java/net/openhft/chronicle/map/Issue58.java @@ -19,8 +19,8 @@ import static java.util.stream.Collectors.toMap; public class Issue58 { - File mapFile = new File("string-to-uuid.dat"); - File reverseMapFile = new File("uuid-to-string.dat"); + final File mapFile = new File("string-to-uuid.dat"); + final File reverseMapFile = new File("uuid-to-string.dat"); public static void main(String... args) { Map map = new HashMap<>(); @@ -108,7 +108,7 @@ public void test2(Map data) throws IOException { System.out.println("BB" + " == " + reverseMap.get(uuid)); System.out.println(uuid + " == " + map.get("BB")); //returns null System.out.println("despite all data being present:"); - map.entrySet().forEach(e -> System.out.println(e.getKey() + "->" + e.getValue())); + map.forEach((key, value) -> System.out.println(key + "->" + value)); reverseMap.forEach((k, v) -> System.out.println(k + " -> " + v)); } } diff --git a/src/test/java/net/openhft/chronicle/map/Issue60Test.java b/src/test/java/net/openhft/chronicle/map/Issue60Test.java index de450b807..e017e2a82 100644 --- a/src/test/java/net/openhft/chronicle/map/Issue60Test.java +++ b/src/test/java/net/openhft/chronicle/map/Issue60Test.java @@ -43,11 +43,11 @@ public void issue60Test() { @Test(expected = IllegalArgumentException.class) public void maxBloatFactorShouldBeLessThan1000() { - ChronicleMapBuilder.of(String.class, String.class).maxBloatFactor(1000.01); + ChronicleMapBuilder.of(String.class, String.class).maxBloatFactor(1000.01); } @Test(expected = IllegalArgumentException.class) public void testIllegalMaxBloatFactor() { - ChronicleMapBuilder.of(Object.class, Object.class).maxBloatFactor(0.0); + ChronicleMapBuilder.of(Object.class, Object.class).maxBloatFactor(0.0); } } diff --git a/src/test/java/net/openhft/chronicle/map/Issue62ChronicleClient.java b/src/test/java/net/openhft/chronicle/map/Issue62ChronicleClient.java index 7917ba301..ba632065b 100644 --- a/src/test/java/net/openhft/chronicle/map/Issue62ChronicleClient.java +++ b/src/test/java/net/openhft/chronicle/map/Issue62ChronicleClient.java @@ -5,7 +5,7 @@ public class Issue62ChronicleClient { - public static void main(String[] args) throws Exception { + public static void main(String[] args) { /*prepare(MAP_FILE_B); ChronicleMapBuilder cityPostalCodesMapBuilder = diff --git a/src/test/java/net/openhft/chronicle/map/Issue62ChronicleServer.java b/src/test/java/net/openhft/chronicle/map/Issue62ChronicleServer.java deleted file mode 100644 index 086450211..000000000 --- a/src/test/java/net/openhft/chronicle/map/Issue62ChronicleServer.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright 2013-2025 chronicle.software; SPDX-License-Identifier: Apache-2.0 - */ -package net.openhft.chronicle.map; - -import net.openhft.chronicle.core.OS; -import net.openhft.chronicle.core.util.Time; - -import java.io.File; -import java.nio.file.Paths; - -public class Issue62ChronicleServer { - - final static String STR = - //"This is just a long string, which causes sink to fail for some reason."; - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; - final static File MAP_FILE_B = - Paths.get(OS.getTarget(), Time.uniqueId() + "map.b").toFile(); - private final static File MAP_FILE_A = - Paths.get(OS.getTarget(), Time.uniqueId() + "map.a").toFile(); - - static void prepare(File file) { - if (file.exists()) - file.delete(); - file.deleteOnExit(); - } - - public static void main(String[] args) throws Exception { -/* - prepare(MAP_FILE_A); - - ChronicleMapBuilder cityPostalCodesMapBuilder = - ChronicleMapBuilder.of(String.class, Long.class) - //.averageKeySize(100) - .averageKey(STR) - .entries(50_000); - - ((ChronicleHashBuilderPrivateAPI) cityPostalCodesMapBuilder.privateAPI()) - .replication((byte) 1); - - ChronicleMap cityPostalCodes = - cityPostalCodesMapBuilder.createPersistedTo(MAP_FILE_A); - - for (int i = 0; i < 100; i++) { - cityPostalCodes.put(STR + i, (long) i); - } - - System.out.println("Map created"); - Jvm.pause(15000); -*/ - } -} diff --git a/src/test/java/net/openhft/chronicle/map/Issue63Test.java b/src/test/java/net/openhft/chronicle/map/Issue63Test.java index 67488f847..5ee955de8 100644 --- a/src/test/java/net/openhft/chronicle/map/Issue63Test.java +++ b/src/test/java/net/openhft/chronicle/map/Issue63Test.java @@ -331,12 +331,12 @@ public void testKnownItems() throws IOException { knownItemsBuilder.recoverPersistedTo(mapFile, true); assertEquals(5, knownItems2.size()); - /* ids.forEach((id) -> { - System.out.println(knownItems2.get(id.subSequence(0, id.length()))); - });*/ -// knownItems2.forEach((id, list) -> { -// System.out.println(id + " : " + String.join(",", list)); -// }); + /* ids.forEach((id) -> { + System.out.println(knownItems2.get(id.subSequence(0, id.length()))); + });*/ + // knownItems2.forEach((id, list) -> { + // System.out.println(id + " : " + String.join(",", list)); + // }); } } diff --git a/src/test/java/net/openhft/chronicle/map/LargeEntriesTest.java b/src/test/java/net/openhft/chronicle/map/LargeEntriesTest.java index 233425d5d..664a396ae 100644 --- a/src/test/java/net/openhft/chronicle/map/LargeEntriesTest.java +++ b/src/test/java/net/openhft/chronicle/map/LargeEntriesTest.java @@ -21,16 +21,17 @@ */ public class LargeEntriesTest { + static final int ENTRIES = 250; + static final int ENTRY_SIZE = 100 * 1024; + @Test public void testLargeStrings() throws ExecutionException, InterruptedException, IOException { - final int ENTRIES = 250; - final int ENTRY_SIZE = 100 * 1024; File file = File.createTempFile("largeEntries" + System.currentTimeMillis(), ".deleteme"); file.deleteOnExit(); try (final ChronicleMap map = ChronicleMapBuilder .of(String.class, String.class) -// .valueReaderAndDataAccess(, SnappyStringMarshaller.INSTANCE, ) + // .valueReaderAndDataAccess(, SnappyStringMarshaller.INSTANCE, ) .actualSegments(1) // to force an error. .entries(ENTRIES) .averageKeySize(10) @@ -70,16 +71,16 @@ public void run() { } private void warmUpCompression(int entrySize) { -// String value = generateValue(entrySize); -// DirectBytes bytes = DirectStore.allocate(entrySize / 6).bytes(); -// for (int i = 0; i < 5; i++) { -// warmup to compression. -// bytes.clear(); -// SnappyStringMarshaller.INSTANCE.write(bytes, value); -// bytes.flip(); -// SnappyStringMarshaller.INSTANCE.read(bytes); -// } -// bytes.release(); + // String value = generateValue(entrySize); + // DirectBytes bytes = DirectStore.allocate(entrySize / 6).bytes(); + // for (int i = 0; i < 5; i++) { + // warmup to compression. + // bytes.clear(); + // SnappyStringMarshaller.INSTANCE.write(bytes, value); + // bytes.flip(); + // SnappyStringMarshaller.INSTANCE.read(bytes); + // } + // bytes.release(); } @Test @@ -92,24 +93,24 @@ public void testLargeStringsPerf() throws ExecutionException, InterruptedExcepti doLargeEntryPerf(3000, 1024 * 1024); } - private void doLargeEntryPerf(int ENTRIES, final int ENTRY_SIZE) throws IOException, InterruptedException, ExecutionException { - System.out.printf("Testing %,d entries of %,d KB%n", ENTRIES, ENTRY_SIZE / 1024); + private void doLargeEntryPerf(int entries, final int entrySize) throws IOException, InterruptedException, ExecutionException { + System.out.printf("Testing %,d entries of %,d KB%n", entries, entrySize / 1024); File file = File.createTempFile("largeEntries", ".deleteme"); file.deleteOnExit(); final ChronicleMap map = ChronicleMapBuilder .of(String.class, String.class) -// .valueReaderAndDataAccess(, SnappyStringMarshaller.INSTANCE, ) - .entries(ENTRIES) + // .valueReaderAndDataAccess(, SnappyStringMarshaller.INSTANCE, ) + .entries(entries) .averageKeySize(10) - .averageValueSize(ENTRY_SIZE) + .averageValueSize(entrySize) .putReturnsNull(true) .createPersistedTo(file); { -// warmUpCompression(ENTRY_SIZE); + // warmUpCompression(ENTRY_SIZE); int threads = Runtime.getRuntime().availableProcessors(); ExecutorService es = Executors.newFixedThreadPool(threads, new NamedThreadFactory("test")); - final int block = ENTRIES / threads; + final int block = entries / threads; for (int i = 0; i < 3; i++) { long start = System.currentTimeMillis(); List> futureList = new ArrayList<>(); @@ -137,7 +138,7 @@ public void run() { } void exerciseLargeStrings(ChronicleMap map, int start, int finish, int entrySize) { -/* + /* final Thread thisThread = Thread.currentThread(); Thread monitor = new Thread(new Runnable() { @Override @@ -158,7 +159,7 @@ public void run() { } }); monitor.start(); -*/ + */ String value = generateValue(entrySize); for (int i = start; i < finish; i++) { @@ -172,10 +173,10 @@ public void run() { assertNotNull(key, object); assertEquals(key, entrySize, object.length()); } -// monitor.interrupt(); + // monitor.interrupt(); for (int i = start; i < finish; i++) { -// System.out.println(i); + // System.out.println(i); String key = "key-" + i; String object = map.get(key); diff --git a/src/test/java/net/openhft/chronicle/map/LargeMapMain.java b/src/test/java/net/openhft/chronicle/map/LargeMapMain.java index 79336ad15..e0a41d00d 100644 --- a/src/test/java/net/openhft/chronicle/map/LargeMapMain.java +++ b/src/test/java/net/openhft/chronicle/map/LargeMapMain.java @@ -13,7 +13,9 @@ public class LargeMapMain { // static int avgSize = 4096, maxSize = 40_000, entries= 500_000; // average ~= 4K - static int avgSize = 1024, maxSize = 8_000, entries = 1_000_000; // average ~= 1K + static final int avgSize = 1024; + static final int maxSize = 8_000; + static final int entries = 1_000_000; // average ~= 1K public static void main(String[] args) throws IOException { ChronicleMap map = createMap(false); @@ -70,8 +72,7 @@ private static ChronicleMap createMap(boolean sparse .averageValueSize(avgSize) .maxBloatFactor(4) .sparseFile(sparseFile); - ChronicleMap map = builder.createPersistedTo(file); - return map; + return builder.createPersistedTo(file); } private static void generate(Random rand, StringBuilder sb, int length) { diff --git a/src/test/java/net/openhft/chronicle/map/LataTest.java b/src/test/java/net/openhft/chronicle/map/LataTest.java index eacc12f1e..1adf7db8a 100644 --- a/src/test/java/net/openhft/chronicle/map/LataTest.java +++ b/src/test/java/net/openhft/chronicle/map/LataTest.java @@ -8,11 +8,11 @@ public class LataTest { - private static int max = 6000000; - private static int run = 100; + private static final int max = 6000000; + private static final int run = 100; private static int currentRun = 0; - public static void main(String[] args) throws Exception { + public static void main(String[] args) { long startTime = 0; long endTime = 0; diff --git a/src/test/java/net/openhft/chronicle/map/ListenersTest.java b/src/test/java/net/openhft/chronicle/map/ListenersTest.java index 720407844..c38be1e53 100644 --- a/src/test/java/net/openhft/chronicle/map/ListenersTest.java +++ b/src/test/java/net/openhft/chronicle/map/ListenersTest.java @@ -164,18 +164,18 @@ public void put(MapQueryContext q, @Test(expected = IllegalStateException.class) public void testRemoveTwice() { - ChronicleMap map = ChronicleMapBuilder.of(Integer.class, Integer.class).entries(100).create(); - map.put(1, 1); - Iterator> it = map.entrySet().iterator(); - it.next(); - it.remove(); - it.remove(); + ChronicleMap map = ChronicleMapBuilder.of(Integer.class, Integer.class).entries(100).create(); + map.put(1, 1); + Iterator> it = map.entrySet().iterator(); + it.next(); + it.remove(); + it.remove(); } static class CountingEntryOperations implements MapEntryOperations { - AtomicInteger removeCount = new AtomicInteger(); - AtomicInteger insertCount = new AtomicInteger(); - AtomicInteger replaceValueCount = new AtomicInteger(); + final AtomicInteger removeCount = new AtomicInteger(); + final AtomicInteger insertCount = new AtomicInteger(); + final AtomicInteger replaceValueCount = new AtomicInteger(); @Override public Void remove(@NotNull MapEntry entry) { diff --git a/src/test/java/net/openhft/chronicle/map/MapCloseTest.java b/src/test/java/net/openhft/chronicle/map/MapCloseTest.java index 25d2b6351..ecb54347a 100644 --- a/src/test/java/net/openhft/chronicle/map/MapCloseTest.java +++ b/src/test/java/net/openhft/chronicle/map/MapCloseTest.java @@ -125,6 +125,6 @@ public void run() { map.get(1); Assert.assertEquals(1, map.allContexts().size()); ChainingInterface cxt = map.allContexts().get(0).get().get(); - Assert.assertTrue(cxt == map.queryContext(1)); + Assert.assertSame(cxt, map.queryContext(1)); } } diff --git a/src/test/java/net/openhft/chronicle/map/MarkTest.java b/src/test/java/net/openhft/chronicle/map/MarkTest.java index 060abb11f..89148ebbd 100644 --- a/src/test/java/net/openhft/chronicle/map/MarkTest.java +++ b/src/test/java/net/openhft/chronicle/map/MarkTest.java @@ -19,7 +19,7 @@ public class MarkTest { - static int ENTRIES = 25_000_000; + static final int ENTRIES = 25_000_000; private static void test( Function, ChronicleMap> @@ -72,6 +72,6 @@ public void persistedTest() { @Test(expected = IllegalArgumentException.class) public void testNegativeEntriesPerSegment() { - ChronicleMapBuilder.of(Integer.class, Integer.class).entriesPerSegment(-1); + ChronicleMapBuilder.of(Integer.class, Integer.class).entriesPerSegment(-1); } } diff --git a/src/test/java/net/openhft/chronicle/map/MarshallableReaderWriterTest.java b/src/test/java/net/openhft/chronicle/map/MarshallableReaderWriterTest.java index 8279bb734..77785d5da 100644 --- a/src/test/java/net/openhft/chronicle/map/MarshallableReaderWriterTest.java +++ b/src/test/java/net/openhft/chronicle/map/MarshallableReaderWriterTest.java @@ -12,18 +12,17 @@ import org.junit.Assert; import org.junit.Test; -import java.io.IOException; import java.util.Objects; public class MarshallableReaderWriterTest { @Test - public void test() throws IOException { + public void test() { ClassAliasPool.CLASS_ALIASES.addAlias(MyOrder.class); try (ChronicleMap map = ChronicleMap .of(CharSequence.class, MyOrder.class) .entries(10) -// .valueMarshaller(new MarshallableReaderWriter<>(MyOrder.class)) + // .valueMarshaller(new MarshallableReaderWriter<>(MyOrder.class)) .averageKeySize(32) .averageValueSize(64) .create()) { diff --git a/src/test/java/net/openhft/chronicle/map/MemoryLeaksTest.java b/src/test/java/net/openhft/chronicle/map/MemoryLeaksTest.java index a099994dc..dc0339f4e 100644 --- a/src/test/java/net/openhft/chronicle/map/MemoryLeaksTest.java +++ b/src/test/java/net/openhft/chronicle/map/MemoryLeaksTest.java @@ -44,7 +44,7 @@ public class MemoryLeaksTest { private final AtomicInteger serializerCount = new AtomicInteger(); private final List> serializers = new ArrayList<>(); @Rule - public TemporaryFolder folder = new TemporaryFolder(); + public final TemporaryFolder folder = new TemporaryFolder(); private final boolean persisted; private final ChronicleMapBuilder builder; @@ -98,8 +98,8 @@ public void testChronicleMapCollectedAndDirectMemoryReleased() throws IOExceptio System.gc(); Jvm.pause(100); - long nativeMemoryUsedBeforeMap = nativeMemoryUsed(); - int serializersBeforeMap = serializerCount.get(); + final long nativeMemoryUsedBeforeMap = nativeMemoryUsed(); + final int serializersBeforeMap = serializerCount.get(); // the purpose of the test is to find maps which are not closed properly. ChronicleMap map = getMap(); long expectedNativeMemory = nativeMemoryUsedBeforeMap + map.offHeapMemoryUsed(); @@ -178,7 +178,7 @@ expectedNativeMemory, nativeMemoryUsed()), byte[] garbage = new byte[50_000_000]; Thread.sleep(1); } - Assert.assertTrue(serializerCount.get() == serializersBeforeMap); + assertEquals(serializerCount.get(), serializersBeforeMap); // This assertion ensures GC doesn't reclaim the map before or during the loop iteration // above, to ensure that we test that the direct memory and contexts are released because // of the manual map.close(), despite the "leak" of the map object itself. @@ -223,19 +223,17 @@ private void tryCloseFromContext(ChronicleMap map) { private static final class CountedStringReader extends StringSizedReader { private transient MemoryLeaksTest memoryLeaksTest; - private final String creationStackTrace; - private final Cleaner cleaner; CountedStringReader(MemoryLeaksTest memoryLeaksTest) { this.memoryLeaksTest = memoryLeaksTest; this.memoryLeaksTest.serializerCount.incrementAndGet(); this.memoryLeaksTest.serializers.add(new WeakReference<>(this)); - cleaner = CleanerUtils.createCleaner(this, this.memoryLeaksTest.serializerCount::decrementAndGet); + Cleaner cleaner = CleanerUtils.createCleaner(this, this.memoryLeaksTest.serializerCount::decrementAndGet); try (StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter)) { new Exception().printStackTrace(printWriter); printWriter.flush(); - creationStackTrace = stringWriter.toString(); + String creationStackTrace = stringWriter.toString(); } catch (IOException e) { throw new RuntimeException(e); } diff --git a/src/test/java/net/openhft/chronicle/map/MissSizedMapsTest.java b/src/test/java/net/openhft/chronicle/map/MissSizedMapsTest.java index 4221dd40d..9c46bf697 100644 --- a/src/test/java/net/openhft/chronicle/map/MissSizedMapsTest.java +++ b/src/test/java/net/openhft/chronicle/map/MissSizedMapsTest.java @@ -12,10 +12,7 @@ import java.io.InputStreamReader; import java.net.URI; import java.net.URISyntaxException; -import java.nio.file.Files; -import java.nio.file.Paths; import java.util.HashMap; -import java.util.List; import java.util.Map; import java.util.zip.GZIPInputStream; diff --git a/src/test/java/net/openhft/chronicle/map/NestedContextsTest.java b/src/test/java/net/openhft/chronicle/map/NestedContextsTest.java index a14f20e4c..960f23903 100644 --- a/src/test/java/net/openhft/chronicle/map/NestedContextsTest.java +++ b/src/test/java/net/openhft/chronicle/map/NestedContextsTest.java @@ -197,6 +197,6 @@ public void nestedContextsTest() throws ExecutionException, InterruptedException @Test(expected = IllegalArgumentException.class) public void negativeEntriesTest() { - ChronicleMap.of(Integer.class, Set.class).entries(-1L).create(); + ChronicleMap.of(Integer.class, Set.class).entries(-1L).create(); } } diff --git a/src/test/java/net/openhft/chronicle/map/ProcessInstanceLimiterMain.java b/src/test/java/net/openhft/chronicle/map/ProcessInstanceLimiterMain.java index c4e93ac15..8ac691779 100644 --- a/src/test/java/net/openhft/chronicle/map/ProcessInstanceLimiterMain.java +++ b/src/test/java/net/openhft/chronicle/map/ProcessInstanceLimiterMain.java @@ -18,13 +18,11 @@ @SuppressWarnings("this-escape") public class ProcessInstanceLimiterMain implements Runnable { private static final long TIME_UPDATE_INTERVAL = 100L; - private final String sharedMapName; private final Map theSharedMap; private final Callback callback; private final Map localUpdates = new ConcurrentHashMap(); - public ProcessInstanceLimiterMain(String sharedMapName, Callback callback) throws IOException { - this.sharedMapName = sharedMapName; + public ProcessInstanceLimiterMain(String sharedMapName, Callback callback) { this.callback = callback; ChronicleMapBuilder builder = ChronicleMapBuilder.of(String.class, Data.class); @@ -112,9 +110,9 @@ public void setMaxNumberOfProcessesOfType(String processType, int maxNumberOfPro } public interface Callback { - public void tooManyProcessesOfType(String processType); + void tooManyProcessesOfType(String processType); - public void noDefinitionForProcessesOfType(String processType); + void noDefinitionForProcessesOfType(String processType); } public static class Data implements Serializable { @@ -122,9 +120,9 @@ public static class Data implements Serializable { * generated serialVersionUID */ private static final long serialVersionUID = 9163018396438735118L; - String processType; - int maxNumberOfProcessesAllowed; - long[] time; + final String processType; + final int maxNumberOfProcessesAllowed; + final long[] time; public Data(String processType, int maxNumberOfProcessesAllowed) { this.processType = processType; @@ -134,7 +132,7 @@ public Data(String processType, int maxNumberOfProcessesAllowed) { } public static class IntWrapper { - int intValue; + final int intValue; public IntWrapper(int intValue) { this.intValue = intValue; diff --git a/src/test/java/net/openhft/chronicle/map/RecoverTest.java b/src/test/java/net/openhft/chronicle/map/RecoverTest.java index dd43296e1..0380d9ff6 100644 --- a/src/test/java/net/openhft/chronicle/map/RecoverTest.java +++ b/src/test/java/net/openhft/chronicle/map/RecoverTest.java @@ -31,7 +31,7 @@ public class RecoverTest { - Logger LOG = LoggerFactory.getLogger(RecoverTest.class); + private static final Logger LOG = LoggerFactory.getLogger(RecoverTest.class); ReplicatedChronicleMap map; diff --git a/src/test/java/net/openhft/chronicle/map/RecursiveRefereneChMapTest.java b/src/test/java/net/openhft/chronicle/map/RecursiveRefereneChMapTest.java index 93b1b3834..c4cd0d965 100644 --- a/src/test/java/net/openhft/chronicle/map/RecursiveRefereneChMapTest.java +++ b/src/test/java/net/openhft/chronicle/map/RecursiveRefereneChMapTest.java @@ -17,7 +17,7 @@ public class RecursiveRefereneChMapTest { public static final String TMP = OS.getTarget(); @Test - public void testRecursive() throws IOException { + public void testRecursive() { File file = new File(TMP + "/test." + Time.uniqueId() + ".tmp"); file.deleteOnExit(); Map map = ChronicleMapBuilder.of(String.class, StupidCycle.class) diff --git a/src/test/java/net/openhft/chronicle/map/ReplicatedChronicleMapTest.java b/src/test/java/net/openhft/chronicle/map/ReplicatedChronicleMapTest.java index 26df07db8..e23cf52d1 100644 --- a/src/test/java/net/openhft/chronicle/map/ReplicatedChronicleMapTest.java +++ b/src/test/java/net/openhft/chronicle/map/ReplicatedChronicleMapTest.java @@ -8,7 +8,6 @@ import net.openhft.chronicle.map.jsr166.JSR166TestCase; import org.junit.Test; -import java.io.IOException; import java.util.*; import static org.junit.Assert.*; @@ -75,14 +74,14 @@ public void testClear() { * Maps with same contents are equal */ @Test - public void testEquals() throws IOException { + public void testEquals() { try (ChronicleMap map1 = map5(); ChronicleMap map2 = map5()) { assertEquals(map1, map2); assertEquals(map2, map1); map1.clear(); - assertFalse(map1.equals(map2)); - assertFalse(map2.equals(map1)); + assertNotEquals(map1, map2); + assertNotEquals(map2, map1); } } @@ -120,66 +119,6 @@ public void testContainsValue() { } } - /* - Inserted elements that are subclasses of the same Comparable - class are found. - */ - /* @Test public void testComparableFamily() throws IOException { - ChronicleMap m = - newShmBiBoolean(); - for (int i = 0; i < 1000; i++) { - assertTrue(m.put(new CI(i), true) == null); - } - for (int i = 0; i < 1000; i++) { - assertTrue(m.containsKey(new CI(i))); - assertTrue(m.containsKey(new DI(i))); - } - }*/ - - /* - TODO : fix test - Elements of classes with erased generic type parameters based - on Comparable can be inserted and found. - */ - /* @Test public void testGenericComparable() throws IOException { - ChronicleMap m = - newShmBiBoolean(); - for (int i = 0; i < 1000; i++) { - BI bi = new BI(i); - BS bs = new BS(String.valueOf(i)); - LexicographicList bis = new LexicographicList(bi); - LexicographicList bss = new LexicographicList(bs); - assertTrue(m.putIfAbsent(bis, true) == null); - assertTrue(m.containsKey(bis)); - if (m.putIfAbsent(bss, true) == null) - assertTrue(m.containsKey(bss)); - assertTrue(m.containsKey(bis)); - } - for (int i = 0; i < 1000; i++) { - assertTrue(m.containsKey(new ArrayList(Collections.singleton(new BI(i))))); - } - } -*/ - - /* - Elements of non-comparable classes equal to those of classes - with erased generic type parameters based on Comparable can be - inserted and found. - */ - /* @Test public void testGenericComparable2() throws IOException { - ChronicleMap m = - newShmListBoolean(); - for (int i = 0; i < 1000; i++) { - m.put(new ArrayList(Collections.singleton(new BI(i))), true); - } - - for (int i = 0; i < 1000; i++) { - LexicographicList bis = new LexicographicList(new BI(i)); - assertTrue(m.containsKey(bis)); - } - } -*/ - /** * get returns the correct element at the given key, or null if not present */ @@ -239,7 +178,7 @@ public void testKeySetToArray() { * Values.toArray contains all values */ @Test - public void testValuesToArray() throws IOException { + public void testValuesToArray() { try (ChronicleMap map = map5()) { Collection v = map.values(); ArrayList s = new ArrayList<>(map.values()); @@ -252,21 +191,6 @@ public void testValuesToArray() throws IOException { } } - /* - TODO : enumeration returns an enumeration containing the correct - elements - */ - /* @Test public void testEnumeration() throws IOException { - ChronicleMap map = map5(); - Enumeration e = map.elements(); - int count = 0; - while (e.hasMoreElements()) { - count++; - e.nextElement(); - } - assertEquals(5, count); - }*/ - /** * entrySet.toArray contains all entries */ @@ -299,20 +223,6 @@ public void testValues() { } } - /* - TODO : keys returns an enumeration containing all the keys from the map - */ - /* @Test public void testKeys() throws IOException { - ChronicleMap map = map5(); - Enumeration e = map.keys(); - int count = 0; - while (e.hasMoreElements()) { - count++; - e.nextElement(); - } - assertEquals(5, count); - }*/ - /** * entrySet contains all pairs */ @@ -321,9 +231,8 @@ public void testEntrySet() { try (ChronicleMap map = map5()) { Set s = map.entrySet(); assertEquals(5, s.size()); - Iterator it = s.iterator(); - while (it.hasNext()) { - Map.Entry e = (Map.Entry) it.next(); + for (Object o : s) { + Map.Entry e = (Map.Entry) o; assertTrue( (e.getKey().equals(JSR166TestCase.one) && "A".contentEquals(e.getValue())) || @@ -481,10 +390,12 @@ public void testToString() { */ @Test public void testGet_NullPointerException() { - try (ChronicleMap c = newShmIntString();) { + try (ChronicleMap c = newShmIntString()) { c.get(null); - shouldThrow(); + assertThrows(); } catch (NullPointerException | IllegalArgumentException success) { + // expected + return; } } @@ -496,8 +407,10 @@ public void testContainsKey_NullPointerException() { try (ChronicleMap c = newShmIntString()) { c.containsKey(null); - shouldThrow(); + assertThrows(); } catch (NullPointerException | IllegalArgumentException success) { + // expected + return; } } @@ -506,10 +419,12 @@ public void testContainsKey_NullPointerException() { */ @Test public void testPut1_NullPointerException() { - try (ChronicleMap c = newShmIntString();) { + try (ChronicleMap c = newShmIntString()) { c.put(null, "whatever"); - shouldThrow(); + assertThrows(); } catch (NullPointerException | IllegalArgumentException success) { + // expected + return; } } @@ -520,8 +435,10 @@ public void testPut1_NullPointerException() { public void testPut2_NullPointerException() { try (ChronicleMap c = newShmIntString()) { c.put(JSR166TestCase.notPresent, null); - shouldThrow(); + assertThrows(); } catch (NullPointerException | IllegalArgumentException success) { + // expected + return; } } @@ -530,48 +447,15 @@ public void testPut2_NullPointerException() { */ @Test public void testPutIfAbsent1_NullPointerException() { - try (ChronicleMap c = newShmIntString();) { + try (ChronicleMap c = newShmIntString()) { c.putIfAbsent(null, "whatever"); - shouldThrow(); + assertThrows(); } catch (NullPointerException | IllegalArgumentException success) { + // expected + return; } } - // Exception tests - - /* - TODO : Cannot create with negative capacity - */ - /* @Test public void testConstructor1() { - try { - newShmIntString(-1, 0, 1); - shouldThrow(); - } catch (IllegalArgumentException success) { - } - }*/ - - /* - TODO : Cannot create with negative concurrency level - */ - /*@Test public void testConstructor2() { - try { - newShmIntString(1, 0, -1); - shouldThrow(); - } catch (IllegalArgumentException success) { - } - }*/ - - /* - TODO :Cannot create with only negative capacity - */ - /* @Test public void testConstructor3() { - try { - newShmIntString(-1); - shouldThrow(); - } catch (IllegalArgumentException success) { - } - }*/ - /** * replace(null, x) throws NPE */ @@ -579,8 +463,10 @@ public void testPutIfAbsent1_NullPointerException() { public void testReplace_NullPointerException() { try (ChronicleMap c = newShmIntString()) { c.replace(null, "whatever"); - shouldThrow(); + assertThrows(); } catch (NullPointerException | IllegalArgumentException success) { + // expected + return; } } @@ -588,40 +474,16 @@ public void testReplace_NullPointerException() { * replace(null, x, y) throws NPE */ @Test - public void testReplaceValue_NullPointerException() throws IOException { - try (ChronicleMap c = newShmIntString();) { + public void testReplaceValue_NullPointerException() { + try (ChronicleMap c = newShmIntString()) { c.replace(null, "A", "whatever"); - shouldThrow(); + assertThrows(); } catch (NullPointerException | IllegalArgumentException success) { + // expected + return; } } - /* - containsValue(null) throws NPE - */ -/* @Test public void testContainsValue_NullPointerException() throws IOException { - try { - ChronicleMap c = newShmIntString(5); - c.containsValue(null); - shouldThrow(); - } catch (NullPointerException|IllegalArgumentException success) { - } - }*/ - - /* - todo : contains(null) throws NPE - */ -/* - @Test public void testContains_NullPointerException() throws IOException { - try { - ChronicleMap c = newShmIntString(5); - c.contains(null); - shouldThrow(); - } catch (NullPointerException|IllegalArgumentException success) { - } - } -*/ - /** * putIfAbsent(x, null) throws NPE */ @@ -629,8 +491,10 @@ public void testReplaceValue_NullPointerException() throws IOException { public void testPutIfAbsent2_NullPointerException() { try (ChronicleMap c = newShmIntString()) { c.putIfAbsent(JSR166TestCase.notPresent, null); - shouldThrow(); + assertThrows(); } catch (NullPointerException | IllegalArgumentException success) { + // expected + return; } } @@ -639,10 +503,12 @@ public void testPutIfAbsent2_NullPointerException() { */ @Test public void testReplace2_NullPointerException() { - try (ChronicleMap c = newShmIntString();) { + try (ChronicleMap c = newShmIntString()) { c.replace(JSR166TestCase.notPresent, null); - shouldThrow(); + assertThrows(); } catch (NullPointerException | IllegalArgumentException success) { + // expected + return; } } @@ -651,10 +517,12 @@ public void testReplace2_NullPointerException() { */ @Test public void testReplaceValue2_NullPointerException() { - try (ChronicleMap c = newShmIntString();) { + try (ChronicleMap c = newShmIntString()) { c.replace(JSR166TestCase.notPresent, null, "A"); - shouldThrow(); + assertThrows(); } catch (NullPointerException | IllegalArgumentException success) { + // expected + return; } } @@ -665,8 +533,10 @@ public void testReplaceValue2_NullPointerException() { public void testReplaceValue3_NullPointerException() { try (ChronicleMap c = newShmIntString()) { c.replace(JSR166TestCase.notPresent, "A", null); - shouldThrow(); + assertThrows(); } catch (NullPointerException | IllegalArgumentException success) { + // expected + return; } } @@ -675,11 +545,13 @@ public void testReplaceValue3_NullPointerException() { */ @Test public void testRemove1_NullPointerException() { - try (ChronicleMap c = newShmStringString();) { + try (ChronicleMap c = newShmStringString()) { c.put("sadsdf", "asdads"); c.remove(null); - shouldThrow(); + assertThrows(); } catch (NullPointerException | IllegalArgumentException success) { + // expected + return; } } @@ -688,11 +560,13 @@ public void testRemove1_NullPointerException() { */ @Test public void testRemove2_NullPointerException() { - try (ChronicleMap c = newShmStringString();) { + try (ChronicleMap c = newShmStringString()) { c.put("sadsdf", "asdads"); c.remove(null, "whatever"); - shouldThrow(); + assertThrows(); } catch (NullPointerException | IllegalArgumentException success) { + // expected + return; } } @@ -700,129 +574,10 @@ public void testRemove2_NullPointerException() { * remove(x, null) returns false */ @Test - public void testRemove3() throws IOException { + public void testRemove3() { try (ChronicleMap c = newShmStringString()) { c.put("sadsdf", "asdads"); assertFalse(c.remove("sadsdf", null)); } } - - // classes for testing Comparable fallbacks - static class BI implements Comparable { - private final int value; - - BI(int value) { - this.value = value; - } - - public int compareTo(BI other) { - return Integer.compare(value, other.value); - } - - public boolean equals(Object x) { - return (x instanceof BI) && ((BI) x).value == value; - } - - public int hashCode() { - return 42; - } - } - - static class CI extends BI { - CI(int value) { - super(value); - } - } - - static class DI extends BI { - DI(int value) { - super(value); - } - } - - static class BS implements Comparable { - private final String value; - - BS(String value) { - this.value = value; - } - - public int compareTo(BS other) { - return value.compareTo(other.value); - } - - public boolean equals(Object x) { - return (x instanceof BS) && value.equals(((BS) x).value); - } - - public int hashCode() { - return 42; - } - } - - static class LexicographicList> extends ArrayList - implements Comparable> { - private static final long serialVersionUID = 0; - static long total; - static long n; - - LexicographicList(Collection c) { - super(c); - } - - LexicographicList(E e) { - super(Collections.singleton(e)); - } - - public int compareTo(LexicographicList other) { - long start = System.currentTimeMillis(); - int common = Math.min(size(), other.size()); - int r = 0; - for (int i = 0; i < common; i++) { - if ((r = get(i).compareTo(other.get(i))) != 0) - break; - } - if (r == 0) - r = Integer.compare(size(), other.size()); - total += System.currentTimeMillis() - start; - n++; - return r; - } - } - - /* - A deserialized map equals original - */ - /* @Test public void testSerialization() { - Map x = map5(); - Map y = serialClone(x); - - assertNotSame(x, y); - assertEquals(x.size(), y.size()); - assertEquals(x, y); - assertEquals(y, x); - }*/ - - /* - TODO : SetValue of an EntrySet entry sets value in the map. - */ - /*@Test public void testSetValueWriteThrough() { - // Adapted from a bug report by Eric Zoerner - ChronicleMap map = newShmIntString(2, 5.0f, 1); - assertTrue(map.isEmpty()); - for (int i = 0; i < 20; i++) - map.put(new Integer(i), new Integer(i)); - assertFalse(map.isEmpty()); - Map.Entry entry1 = (Map.Entry) map.entrySet().iterator().next(); - // Unless it happens to be first (in which case remainder of - // test is skipped), remove a possibly-colliding key from map - // which, under some implementations, may cause entry1 to be - // cloned in map - if (!entry1.getKey().equals(new Integer(16))) { - map.remove(new Integer(16)); - entry1.setValue("XYZ"); - assertTrue(map.containsValue("XYZ")); // fails if write-through broken - } - }*/ - } diff --git a/src/test/java/net/openhft/chronicle/map/ReplicationCheckingMap.java b/src/test/java/net/openhft/chronicle/map/ReplicationCheckingMap.java index db977a5a0..3a45b58c7 100644 --- a/src/test/java/net/openhft/chronicle/map/ReplicationCheckingMap.java +++ b/src/test/java/net/openhft/chronicle/map/ReplicationCheckingMap.java @@ -25,8 +25,8 @@ @SuppressWarnings({"rawtypes", "unchecked", "serial"}) public class ReplicationCheckingMap implements ChronicleMap { - ChronicleMap map1; - ChronicleMap map2; + final ChronicleMap map1; + final ChronicleMap map2; public ReplicationCheckingMap(ChronicleMap map1, ChronicleMap map2) { this.map1 = map1; diff --git a/src/test/java/net/openhft/chronicle/map/SerializableTest.java b/src/test/java/net/openhft/chronicle/map/SerializableTest.java index 93f64c59a..234417707 100644 --- a/src/test/java/net/openhft/chronicle/map/SerializableTest.java +++ b/src/test/java/net/openhft/chronicle/map/SerializableTest.java @@ -155,14 +155,13 @@ public void test2f() { @NotNull private static String expected() { - String expected = IntStream.range(0, 4096) + return IntStream.range(0, 4096) .mapToObj(i -> i % 50 == 0 ? String.format("\n%04d", i) : "" + i % 10) .collect(Collectors.joining("")); - return expected; } public static class Foo implements Serializable { - public String x; + public final String x; Foo(int length) { this.x = "x" + IntStream.range(0, length) diff --git a/src/test/java/net/openhft/chronicle/map/TrickyContextCasesTest.java b/src/test/java/net/openhft/chronicle/map/TrickyContextCasesTest.java index fc4453e72..fa61a9d75 100644 --- a/src/test/java/net/openhft/chronicle/map/TrickyContextCasesTest.java +++ b/src/test/java/net/openhft/chronicle/map/TrickyContextCasesTest.java @@ -32,7 +32,7 @@ public void nestedContextsSameKeyTest() { try (ExternalMapQueryContext q = map.queryContext(1)) { q.writeLock().lock(); // assume the value is 2 - IntValue v2 = q.entry().value().get(); + final IntValue v2 = q.entry().value().get(); // this call should throw ISE, as accessing the key 1 in a nested context, but if not... map.remove(1); v.setValue(3); diff --git a/src/test/java/net/openhft/chronicle/map/ValueAlignmentRelocationTest.java b/src/test/java/net/openhft/chronicle/map/ValueAlignmentRelocationTest.java index 6ff7374a6..64a87302c 100644 --- a/src/test/java/net/openhft/chronicle/map/ValueAlignmentRelocationTest.java +++ b/src/test/java/net/openhft/chronicle/map/ValueAlignmentRelocationTest.java @@ -92,9 +92,9 @@ public void testValueAlignmentRelocation() throws IOException { map.put(new byte[]{(byte) i}, new byte[]{(byte) i}); map.put(("Hello" + i).getBytes(), "world".getBytes()); } -// System.out.println("firstKeySize=" + firstKeySize + ",second key=" + secondKeySize); + // System.out.println("firstKeySize=" + firstKeySize + ",second key=" + secondKeySize); Assert.assertEquals(Arrays.toString(map.get(firstKey)), Arrays.toString(thirdValue)); - Assert.assertTrue(Arrays.equals(map.get(firstKey), thirdValue)); + Assert.assertArrayEquals(map.get(firstKey), thirdValue); } } } @@ -121,24 +121,24 @@ public void testValueAlignmentRelocationNoRandomTest() throws IOException { for (int j = i + 1; j <= i + 10; j++) { map.clear(); - byte[] _austi = "abcdefghijklmnopqrstuvwxyz".substring(0, k).getBytes(ISO_8859_1); - byte[] _shorter = "1234567890".substring(0, i).getBytes(ISO_8859_1); - byte[] _h = "h".getBytes(ISO_8859_1); - byte[] _a = "a".getBytes(ISO_8859_1); + byte[] prefix = "abcdefghijklmnopqrstuvwxyz".substring(0, k).getBytes(ISO_8859_1); + byte[] shorter = "1234567890".substring(0, i).getBytes(ISO_8859_1); + byte[] letterH = "h".getBytes(ISO_8859_1); + byte[] letterA = "a".getBytes(ISO_8859_1); String expected = "abcdefghijklmnopqrstuvwxyz".substring(0, j); - byte[] _longer = expected.getBytes(ISO_8859_1); - byte[] _Hello = "Hello".getBytes(ISO_8859_1); - byte[] _world = "world".getBytes(ISO_8859_1); + byte[] longer = expected.getBytes(ISO_8859_1); + final byte[] hello = "Hello".getBytes(ISO_8859_1); + final byte[] world = "world".getBytes(ISO_8859_1); - map.put(_austi, _shorter); - map.put(_h, _a); + map.put(prefix, shorter); + map.put(letterH, letterA); - map.put(_austi, _longer); - String actual0 = toString(map.get(_austi)); + map.put(prefix, longer); + String actual0 = toString(map.get(prefix)); Assert.assertEquals(expected, actual0); - map.put(_Hello, _world); - String actual = toString(map.get(_austi)); + map.put(hello, world); + String actual = toString(map.get(prefix)); if (expected.equals(actual)) Assert.assertEquals(expected, actual); diff --git a/src/test/java/net/openhft/chronicle/map/VeryLargeMapMain.java b/src/test/java/net/openhft/chronicle/map/VeryLargeMapMain.java index 5f482cb79..45e260a8a 100644 --- a/src/test/java/net/openhft/chronicle/map/VeryLargeMapMain.java +++ b/src/test/java/net/openhft/chronicle/map/VeryLargeMapMain.java @@ -13,7 +13,9 @@ import java.util.stream.IntStream; public class VeryLargeMapMain { - static int avgSize = 16000, maxSize = 190_000, entries = 50_000_000; // average ~= 16K + static final int avgSize = 16000; + static final int maxSize = 190_000; + static final int entries = 50_000_000; // average ~= 16K public static void main(String[] args) throws IOException { ChronicleMap map = createMap(true); @@ -59,10 +61,9 @@ private static ChronicleMap createMap(boolean sparse .entries(entries) .averageKeySize(64) .averageValueSize(avgSize) -// .maxBloatFactor(2) + // .maxBloatFactor(2) .sparseFile(sparseFile); - ChronicleMap map = builder.createPersistedTo(file); - return map; + return builder.createPersistedTo(file); } private static void generate(Random rand, StringBuilder sb, int length) { diff --git a/src/test/java/net/openhft/chronicle/map/WriteThroughputTest.java b/src/test/java/net/openhft/chronicle/map/WriteThroughputTest.java index 1bccefcc2..abe0e89b2 100644 --- a/src/test/java/net/openhft/chronicle/map/WriteThroughputTest.java +++ b/src/test/java/net/openhft/chronicle/map/WriteThroughputTest.java @@ -51,7 +51,7 @@ public void bandwidthTest() throws IOException { .of(CharSequence.class, CharSequence.class) .entries(count * 3 / 2) .averageValueSize(size / 4) -// .valueReaderAndDataAccess(, SnappyStringMarshaller.INSTANCE, ) + // .valueReaderAndDataAccess(, SnappyStringMarshaller.INSTANCE, ) .putReturnsNull(true) .createPersistedTo(file2)) { diff --git a/src/test/java/net/openhft/chronicle/map/example/LotsOfEntriesMain.java b/src/test/java/net/openhft/chronicle/map/example/LotsOfEntriesMain.java index 45fc89a49..d0391d0a3 100644 --- a/src/test/java/net/openhft/chronicle/map/example/LotsOfEntriesMain.java +++ b/src/test/java/net/openhft/chronicle/map/example/LotsOfEntriesMain.java @@ -22,9 +22,9 @@ interface MyFloats { @Array(length = 6) - public void setValueAt(int index, float f); + void setValueAt(int index, float f); - public float getValueAt(int index); + float getValueAt(int index); } /** * Created by peter.lawrey on 19/12/14. diff --git a/src/test/java/net/openhft/chronicle/map/example/PointListSerializationTest.java b/src/test/java/net/openhft/chronicle/map/example/PointListSerializationTest.java index 793d0f02e..26256ae87 100644 --- a/src/test/java/net/openhft/chronicle/map/example/PointListSerializationTest.java +++ b/src/test/java/net/openhft/chronicle/map/example/PointListSerializationTest.java @@ -29,13 +29,13 @@ public void testComplexSerialization() { .averageKeySize(4) .averageValueSize(1000) .create()) { - A obj_A = new A(); - obj_A.str_ = "a"; - obj_A.list_ = new ArrayList<>(); + A objectA = new A(); + objectA.value = "a"; + objectA.items = new ArrayList<>(); B b = new B(); - b.str_ = "b"; - obj_A.list_.add(b); - map.put("KEY1", obj_A); + b.text = "b"; + objectA.items.add(b); + map.put("KEY1", objectA); map.get("KEY1"); } } @@ -49,12 +49,12 @@ private AMarshaller() { @Override public void write(Bytes out, @NotNull A toWrite) { - out.writeUtf8(toWrite.str_); - if (toWrite.list_ != null) { - int size = toWrite.list_.size(); + out.writeUtf8(toWrite.value); + if (toWrite.items != null) { + int size = toWrite.items.size(); out.writeStopBit(size); for (int i = 0; i < size; i++) { - toWrite.list_.get(i).writeMarshallable(out); + toWrite.items.get(i).writeMarshallable(out); } } else { out.writeStopBit(-1); @@ -66,24 +66,24 @@ public void write(Bytes out, @NotNull A toWrite) { public A read(Bytes in, A using) { if (using == null) using = new A(); - using.str_ = in.readUtf8(); + using.value = in.readUtf8(); int size = (int) in.readStopBit(); if (size >= 0) { - if (using.list_ == null) { - using.list_ = new ArrayList<>(size); + if (using.items == null) { + using.items = new ArrayList<>(size); } else { - using.list_.clear(); - if (using.list_ instanceof ArrayList) - ((ArrayList) using.list_).ensureCapacity(size); + using.items.clear(); + if (using.items instanceof ArrayList) + ((ArrayList) using.items).ensureCapacity(size); } for (int i = 0; i < size; i++) { B b = new B(); b.readMarshallable(in); - using.list_.add(b); + using.items.add(b); } } else { assert size == -1; - using.list_ = null; + using.items = null; } return using; } @@ -96,21 +96,21 @@ public AMarshaller readResolve() { } static class A { - String str_; - List list_; + String value; + List items; } static class B implements BytesMarshallable { - String str_; + String text; @Override public void readMarshallable(BytesIn in) { - str_ = in.readUtf8(); + text = in.readUtf8(); } @Override public void writeMarshallable(BytesOut out) { - out.writeUtf8(str_); + out.writeUtf8(text); } } } diff --git a/src/test/java/net/openhft/chronicle/map/fromdocs/CharSequenceCustomEncodingBytesReader.java b/src/test/java/net/openhft/chronicle/map/fromdocs/CharSequenceCustomEncodingBytesReader.java index f07779592..2d7af1a3e 100644 --- a/src/test/java/net/openhft/chronicle/map/fromdocs/CharSequenceCustomEncodingBytesReader.java +++ b/src/test/java/net/openhft/chronicle/map/fromdocs/CharSequenceCustomEncodingBytesReader.java @@ -63,11 +63,11 @@ public CharSequence read(Bytes in, @Nullable CharSequence using) { sb = new StringBuilder(csLength); } - int remainingBytes = in.readInt(); charsetDecoder.reset(); inputBuffer.clear(); outputBuffer.clear(); boolean endOfInput = false; + int remainingBytes = in.readInt(); // this loop inspired by the CharsetDecoder.decode(ByteBuffer) implementation while (true) { if (!endOfInput) { diff --git a/src/test/java/net/openhft/chronicle/map/fromdocs/CharSequenceCustomEncodingBytesWriter.java b/src/test/java/net/openhft/chronicle/map/fromdocs/CharSequenceCustomEncodingBytesWriter.java index 0f047f051..46eaf7765 100644 --- a/src/test/java/net/openhft/chronicle/map/fromdocs/CharSequenceCustomEncodingBytesWriter.java +++ b/src/test/java/net/openhft/chronicle/map/fromdocs/CharSequenceCustomEncodingBytesWriter.java @@ -57,7 +57,7 @@ private void initTransients() { public void write(Bytes out, @NotNull CharSequence cs) { // Write the actual cs length for accurate StringBuilder.ensureCapacity() while reading out.writeStopBit(cs.length()); - long encodedSizePos = out.writePosition(); + final long encodedSizePos = out.writePosition(); out.writeSkip(4); charsetEncoder.reset(); inputBuffer.clear(); diff --git a/src/test/java/net/openhft/chronicle/map/fromdocs/OpenJDKAndHashMapExamplesTest.java b/src/test/java/net/openhft/chronicle/map/fromdocs/OpenJDKAndHashMapExamplesTest.java index 08ab4a1f1..b31eef57f 100644 --- a/src/test/java/net/openhft/chronicle/map/fromdocs/OpenJDKAndHashMapExamplesTest.java +++ b/src/test/java/net/openhft/chronicle/map/fromdocs/OpenJDKAndHashMapExamplesTest.java @@ -38,7 +38,7 @@ public static long parseYYYYMMDD(String s) { } @Test - public void bondExample() throws IOException, InterruptedException { + public void bondExample() throws IOException { File file = new File(TMP + "/chm-myBondPortfolioCHM-" + Time.uniqueId()); file.deleteOnExit(); @@ -94,7 +94,7 @@ public void bondExample() throws IOException, InterruptedException { assertNotNull(c); // found a key and bond has been set // get directly without touching the rest of the record. - long _matDate = bond.getMaturityDate(); + bond.getMaturityDate(); // write just this field, again we need to assume we are the only writer. bond.setMaturityDate(parseYYYYMMDD("20440315")); diff --git a/src/test/java/net/openhft/chronicle/map/fromdocs/acid/ChronicleAcidIsolationGovernor.java b/src/test/java/net/openhft/chronicle/map/fromdocs/acid/ChronicleAcidIsolationGovernor.java index 4a3798956..a3fa42107 100644 --- a/src/test/java/net/openhft/chronicle/map/fromdocs/acid/ChronicleAcidIsolationGovernor.java +++ b/src/test/java/net/openhft/chronicle/map/fromdocs/acid/ChronicleAcidIsolationGovernor.java @@ -20,7 +20,7 @@ public class ChronicleAcidIsolationGovernor implements ChronicleAcidIsolation { private String priorCusip; private Double aCoupon; - public synchronized void put(String cusip, BondVOInterface bond) throws Exception { + public synchronized void put(String cusip, BondVOInterface bond) { System.out.println( " , @t=" + System.currentTimeMillis() + @@ -103,14 +103,13 @@ public void setCompositeChronicleMap(ChronicleMap ccm) } @Override - public synchronized int getTransactionIsolation() throws SQLException { + public synchronized int getTransactionIsolation() { - int iL = this.getTransactionIsolationMap().get(Thread.currentThread()); - return (iL); + return this.getTransactionIsolationMap().get(Thread.currentThread()); } @Override - public synchronized void setTransactionIsolation(int level) throws SQLException { + public synchronized void setTransactionIsolation(int level) { this.getTransactionIsolationMap().put( Thread.currentThread().toString(), @@ -119,7 +118,7 @@ public synchronized void setTransactionIsolation(int level) throws SQLException } @Override - public synchronized void commit() throws SQLException { + public synchronized void commit() { System.out.println( " ,@t=" + System.currentTimeMillis() + " Tx=" + Thread.currentThread().toString().replaceAll(",", ".") + @@ -144,7 +143,7 @@ public synchronized void commit() throws SQLException { } @Override - public synchronized void rollback() throws SQLException { + public synchronized void rollback() { BondVOInterface priorBond = this.getCompositeChronicleMap().get("369604101"); if (priorBond != null) { priorBond.setCoupon(3.50); @@ -177,252 +176,252 @@ public synchronized void rollback() throws SQLException { // is likely the only isolation level Chronicle would accommodate. @Override - public boolean getAutoCommit() throws SQLException { + public boolean getAutoCommit() { return false; } @Override - public void setAutoCommit(boolean autoCommit) throws SQLException { + public void setAutoCommit(boolean autoCommit) { } @Override - public void rollback(Savepoint savepoint) throws SQLException { + public void rollback(Savepoint savepoint) { } @Override - public void close() throws SQLException { + public void close() { } @Override - public Statement createStatement() throws SQLException { + public Statement createStatement() { return null; } @Override - public PreparedStatement prepareStatement(String sql) throws SQLException { + public PreparedStatement prepareStatement(String sql) { return null; } @Override - public CallableStatement prepareCall(String sql) throws SQLException { + public CallableStatement prepareCall(String sql) { return null; } @Override - public String nativeSQL(String sql) throws SQLException { + public String nativeSQL(String sql) { return null; } @Override - public boolean isClosed() throws SQLException { + public boolean isClosed() { return false; } @Override - public DatabaseMetaData getMetaData() throws SQLException { + public DatabaseMetaData getMetaData() { return null; } @Override - public boolean isReadOnly() throws SQLException { + public boolean isReadOnly() { return false; } @Override - public void setReadOnly(boolean readOnly) throws SQLException { + public void setReadOnly(boolean readOnly) { } @Override - public String getCatalog() throws SQLException { + public String getCatalog() { return null; } @Override - public void setCatalog(String catalog) throws SQLException { + public void setCatalog(String catalog) { } @Override - public SQLWarning getWarnings() throws SQLException { + public SQLWarning getWarnings() { return null; } @Override - public void clearWarnings() throws SQLException { + public void clearWarnings() { } @Override - public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { + public Statement createStatement(int resultSetType, int resultSetConcurrency) { return null; } @Override - public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { + public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) { return null; } @Override - public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { + public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) { return null; } @Override - public Map> getTypeMap() throws SQLException { + public Map> getTypeMap() { return null; } @Override - public void setTypeMap(Map> map) throws SQLException { + public void setTypeMap(Map> map) { } @Override - public int getHoldability() throws SQLException { + public int getHoldability() { return 0; } @Override - public void setHoldability(int holdability) throws SQLException { + public void setHoldability(int holdability) { } @Override - public Savepoint setSavepoint() throws SQLException { + public Savepoint setSavepoint() { return null; } @Override - public Savepoint setSavepoint(String name) throws SQLException { + public Savepoint setSavepoint(String name) { return null; } @Override - public void releaseSavepoint(Savepoint savepoint) throws SQLException { + public void releaseSavepoint(Savepoint savepoint) { } @Override - public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { + public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) { return null; } @Override - public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { + public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) { return null; } @Override - public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { + public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) { return null; } @Override - public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { + public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) { return null; } @Override - public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { + public PreparedStatement prepareStatement(String sql, int[] columnIndexes) { return null; } @Override - public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { + public PreparedStatement prepareStatement(String sql, String[] columnNames) { return null; } @Override - public Clob createClob() throws SQLException { + public Clob createClob() { return null; } @Override - public Blob createBlob() throws SQLException { + public Blob createBlob() { return null; } @Override - public NClob createNClob() throws SQLException { + public NClob createNClob() { return null; } @Override - public SQLXML createSQLXML() throws SQLException { + public SQLXML createSQLXML() { return null; } @Override - public boolean isValid(int timeout) throws SQLException { + public boolean isValid(int timeout) { return false; } @Override - public void setClientInfo(String name, String value) throws SQLClientInfoException { + public void setClientInfo(String name, String value) { } @Override - public String getClientInfo(String name) throws SQLException { + public String getClientInfo(String name) { return null; } @Override - public Properties getClientInfo() throws SQLException { + public Properties getClientInfo() { return null; } @Override - public void setClientInfo(Properties properties) throws SQLClientInfoException { + public void setClientInfo(Properties properties) { } @Override - public Array createArrayOf(String typeName, Object[] elements) throws SQLException { + public Array createArrayOf(String typeName, Object[] elements) { return null; } @Override - public Struct createStruct(String typeName, Object[] attributes) throws SQLException { + public Struct createStruct(String typeName, Object[] attributes) { return null; } @Override - public String getSchema() throws SQLException { + public String getSchema() { return null; } @Override - public void setSchema(String schema) throws SQLException { + public void setSchema(String schema) { } @Override - public void abort(Executor executor) throws SQLException { + public void abort(Executor executor) { } @Override - public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException { + public void setNetworkTimeout(Executor executor, int milliseconds) { } @Override - public int getNetworkTimeout() throws SQLException { + public int getNetworkTimeout() { return 0; } @Override - public T unwrap(Class iface) throws SQLException { + public T unwrap(Class iface) { return null; } @Override - public boolean isWrapperFor(Class iface) throws SQLException { + public boolean isWrapperFor(Class iface) { return false; } } diff --git a/src/test/java/net/openhft/chronicle/map/fromdocs/acid/exodus/DirtyReadOffender.java b/src/test/java/net/openhft/chronicle/map/fromdocs/acid/exodus/DirtyReadOffender.java index 05b4e68a2..9a9cd8049 100644 --- a/src/test/java/net/openhft/chronicle/map/fromdocs/acid/exodus/DirtyReadOffender.java +++ b/src/test/java/net/openhft/chronicle/map/fromdocs/acid/exodus/DirtyReadOffender.java @@ -47,7 +47,7 @@ public void run() { " DirtyReadOffender ACQUIRING offHeapLock.writeLock();" ); while ((stamp = this.offHeapLock.writeLock()) == 0) { - ; // none + // none } System.out.println( " @t=" + System.currentTimeMillis() + @@ -102,7 +102,7 @@ public void setIsoLevel(int isoLevel) { this.isoLevel = isoLevel; } - public void setStampedLock(StampedLock _sLock) { - this.offHeapLock = _sLock; + public void setStampedLock(StampedLock stampedLock) { + this.offHeapLock = stampedLock; } } diff --git a/src/test/java/net/openhft/chronicle/map/fromdocs/acid/exodus/DirtyReadTolerance.java b/src/test/java/net/openhft/chronicle/map/fromdocs/acid/exodus/DirtyReadTolerance.java index 82bde83ce..ca456b879 100644 --- a/src/test/java/net/openhft/chronicle/map/fromdocs/acid/exodus/DirtyReadTolerance.java +++ b/src/test/java/net/openhft/chronicle/map/fromdocs/acid/exodus/DirtyReadTolerance.java @@ -15,8 +15,8 @@ public class DirtyReadTolerance { public static void main(String[] args) throws Exception { - System.out.println("DirtyReadOffender,chrAig[" + args[0] + "]coupon=3.50,DirtyReadVictim"); String isoLevel = args[0]; + System.out.println("DirtyReadOffender,chrAig[" + isoLevel + "]coupon=3.50,DirtyReadVictim"); ChronicleMap chm = DirtyReadTolerance.offHeap( @@ -44,10 +44,8 @@ static ChronicleMap offHeap(String operand) throws IOEx .entries(16) .averageKeySize("123456789".length()) .createPersistedTo( - new File( - operand - // "C:\\Users\\buddy\\dev\\shm\\OPERAND_CHRONICLE_MAP" - ) + // "C:\\Users\\buddy\\dev\\shm\\OPERAND_CHRONICLE_MAP" + new File(operand) ); //.create(); } diff --git a/src/test/java/net/openhft/chronicle/map/fromdocs/acid/exodus/DirtyReadVictim.java b/src/test/java/net/openhft/chronicle/map/fromdocs/acid/exodus/DirtyReadVictim.java index 4566dc22c..9be42de02 100644 --- a/src/test/java/net/openhft/chronicle/map/fromdocs/acid/exodus/DirtyReadVictim.java +++ b/src/test/java/net/openhft/chronicle/map/fromdocs/acid/exodus/DirtyReadVictim.java @@ -14,15 +14,15 @@ @SuppressWarnings({"rawtypes", "unchecked"}) public class DirtyReadVictim implements Runnable { - private int isoLevel = ChronicleAcidIsolation.LOWEST_LATENCY; private ChronicleMap chm; private StampedLock offHeapLock; DirtyReadVictim(String isoL) { + int isoLevel = ChronicleAcidIsolation.LOWEST_LATENCY; if (isoL.equals("DIRTY_READ_INTOLERANT")) - this.isoLevel = ChronicleAcidIsolation.DIRTY_READ_INTOLERANT; + isoLevel = ChronicleAcidIsolation.DIRTY_READ_INTOLERANT; else if (isoL.equals("DIRTY_READ_OPTIMISTIC")) - this.isoLevel = ChronicleAcidIsolation.DIRTY_READ_OPTIMISTIC; + isoLevel = ChronicleAcidIsolation.DIRTY_READ_OPTIMISTIC; } @Override @@ -30,10 +30,10 @@ public void run() { Scanner sc = new Scanner(System.in); try { -/* - ben.cotton@rutgers.edu START - */ - Double coupon = 0.00; + /* + ben.cotton@rutgers.edu START + */ + double coupon = 0.00; BondVOInterface bond = newNativeReference(BondVOInterface.class); long stamp = 0; System.out.println( @@ -41,7 +41,7 @@ public void run() { " DirtyReadVictim CALLING offHeapLock.tryOptimisticRead()" ); while ((stamp = this.offHeapLock.tryOptimisticRead()) == 0) { - ; // none + // none } System.out.println( " ,,@t=" + System.currentTimeMillis() + @@ -109,7 +109,7 @@ public void setCraig(ChronicleMap craig) { this.chm = craig; } - public void setStampedLock(StampedLock _sLock) { - this.offHeapLock = _sLock; + public void setStampedLock(StampedLock stampedLock) { + this.offHeapLock = stampedLock; } } diff --git a/src/test/java/net/openhft/chronicle/map/fromdocs/acid/genesis/DirtyReadOffender.java b/src/test/java/net/openhft/chronicle/map/fromdocs/acid/genesis/DirtyReadOffender.java index 9ec2c2494..0f27a758f 100644 --- a/src/test/java/net/openhft/chronicle/map/fromdocs/acid/genesis/DirtyReadOffender.java +++ b/src/test/java/net/openhft/chronicle/map/fromdocs/acid/genesis/DirtyReadOffender.java @@ -47,7 +47,7 @@ public void run() { " DirtyReadOffender ACQUIRING offHeapLock.writeLock();" ); while ((stamp = this.offHeapLock.writeLock()) == 0) { - ; // none + // none } System.out.println( " @t=" + System.currentTimeMillis() + @@ -102,7 +102,7 @@ public void setIsoLevel(int isoLevel) { this.isoLevel = isoLevel; } - public void setStampedLock(StampedLock _sLock) { - this.offHeapLock = _sLock; + public void setStampedLock(StampedLock stampedLock) { + this.offHeapLock = stampedLock; } } diff --git a/src/test/java/net/openhft/chronicle/map/fromdocs/acid/genesis/DirtyReadTolerance.java b/src/test/java/net/openhft/chronicle/map/fromdocs/acid/genesis/DirtyReadTolerance.java index df845916b..2e2f4f08f 100644 --- a/src/test/java/net/openhft/chronicle/map/fromdocs/acid/genesis/DirtyReadTolerance.java +++ b/src/test/java/net/openhft/chronicle/map/fromdocs/acid/genesis/DirtyReadTolerance.java @@ -15,8 +15,8 @@ public class DirtyReadTolerance { public static void main(String[] args) throws Exception { - System.out.println("DirtyReadOffender,chrAig[" + args[0] + "]coupon=3.50,DirtyReadVictim"); String isoLevel = args[0]; + System.out.println("DirtyReadOffender,chrAig[" + isoLevel + "]coupon=3.50,DirtyReadVictim"); ChronicleMap chm = DirtyReadTolerance.offHeap( @@ -44,10 +44,8 @@ static ChronicleMap offHeap(String operand) throws IOEx .entries(16) .averageKeySize("123456789".length()) .createPersistedTo( - new File( - operand - // "C:\\Users\\buddy\\dev\\shm\\OPERAND_CHRONICLE_MAP" - ) + // "C:\\Users\\buddy\\dev\\shm\\OPERAND_CHRONICLE_MAP" + new File(operand) ); //.create(); } diff --git a/src/test/java/net/openhft/chronicle/map/fromdocs/acid/genesis/DirtyReadVictim.java b/src/test/java/net/openhft/chronicle/map/fromdocs/acid/genesis/DirtyReadVictim.java index b5cc0db6b..70f77a937 100644 --- a/src/test/java/net/openhft/chronicle/map/fromdocs/acid/genesis/DirtyReadVictim.java +++ b/src/test/java/net/openhft/chronicle/map/fromdocs/acid/genesis/DirtyReadVictim.java @@ -14,15 +14,15 @@ @SuppressWarnings({"rawtypes", "unchecked"}) public class DirtyReadVictim implements Runnable { - private int isoLevel = ChronicleAcidIsolation.LOWEST_LATENCY; private ChronicleMap chm; private StampedLock offHeapLock; DirtyReadVictim(String isoL) { + int isoLevel = ChronicleAcidIsolation.LOWEST_LATENCY; if (isoL.equals("DIRTY_READ_INTOLERANT")) - this.isoLevel = ChronicleAcidIsolation.DIRTY_READ_INTOLERANT; + isoLevel = ChronicleAcidIsolation.DIRTY_READ_INTOLERANT; else if (isoL.equals("DIRTY_READ_OPTIMISTIC")) - this.isoLevel = ChronicleAcidIsolation.DIRTY_READ_OPTIMISTIC; + isoLevel = ChronicleAcidIsolation.DIRTY_READ_OPTIMISTIC; } @Override @@ -30,10 +30,10 @@ public void run() { Scanner sc = new Scanner(System.in); try { -/* - ben.cotton@rutgers.edu START - */ - Double coupon = 0.00; + /* + ben.cotton@rutgers.edu START + */ + double coupon = 0.00; BondVOInterface bond = newNativeReference(BondVOInterface.class); long stamp = 0; System.out.println( @@ -41,7 +41,7 @@ public void run() { " DirtyReadVictim CALLING offHeapLock.tryOptimisticRead()" ); while ((stamp = this.offHeapLock.tryOptimisticRead()) == 0) { - ; // none + // none } System.out.println( " ,,@t=" + System.currentTimeMillis() + @@ -109,7 +109,7 @@ public void setCraig(ChronicleMap craig) { this.chm = craig; } - public void setStampedLock(StampedLock _sLock) { - this.offHeapLock = _sLock; + public void setStampedLock(StampedLock stampedLock) { + this.offHeapLock = stampedLock; } } diff --git a/src/test/java/net/openhft/chronicle/map/fromdocs/acid/revelations/ChronicleStampedLock.java b/src/test/java/net/openhft/chronicle/map/fromdocs/acid/revelations/ChronicleStampedLock.java index 76747a5a7..21cb45bf3 100644 --- a/src/test/java/net/openhft/chronicle/map/fromdocs/acid/revelations/ChronicleStampedLock.java +++ b/src/test/java/net/openhft/chronicle/map/fromdocs/acid/revelations/ChronicleStampedLock.java @@ -143,13 +143,11 @@ public boolean validate(long stamp) { @Override public long tryWriteLock() { - long l = 0L; - offHeapLock = chm.get("Stamp "); lastWriterT = chm.get("LastWriterTime "); writeLockHolderCount = chmW.get("WriterCount "); - l = offHeapLock.getEntryLockState(); + long l = offHeapLock.getEntryLockState(); if (l != 0L) return 0L; @@ -259,12 +257,12 @@ public long tryReadLock() { @Override public long writeLock() { - long l = 0L; - offHeapLock = chm.get("Stamp "); lastWriterT = chm.get("LastWriterTime "); writeLockHolderCount = chmW.get("WriterCount "); + long l = 0L; + do { System.out.println( " ,@t=" + System.currentTimeMillis() + @@ -373,7 +371,7 @@ public void unlock(long stamp) { } else if (stamp > 0L) { unlockRead(stamp); } else { - ; // none// lock available + // none// lock available } } @@ -441,13 +439,13 @@ public void unlockWrite(long stamp) { ); } -// @Override -// public boolean isWriteLocked() { -// if (this.getReadLockCount() < 0) -// return (Boolean.TRUE); -// else -// return (Boolean.FALSE); -// } + // @Override + // public boolean isWriteLocked() { + // if (this.getReadLockCount() < 0) + // return (Boolean.TRUE); + // else + // return (Boolean.FALSE); + // } @Override public int getReadLockCount() { diff --git a/src/test/java/net/openhft/chronicle/map/fromdocs/acid/revelations/ChronicleStampedLockVOInterface.java b/src/test/java/net/openhft/chronicle/map/fromdocs/acid/revelations/ChronicleStampedLockVOInterface.java index 1b9b1d884..6fdfb3340 100644 --- a/src/test/java/net/openhft/chronicle/map/fromdocs/acid/revelations/ChronicleStampedLockVOInterface.java +++ b/src/test/java/net/openhft/chronicle/map/fromdocs/acid/revelations/ChronicleStampedLockVOInterface.java @@ -11,13 +11,12 @@ interface ChronicleStampedLockVOInterface { long getEntryLockState(); void setEntryLockState(long entryLockState); -// -// @Group(1) -// long getReaderCount(); -// -// void setReaderCount(long rc); /* time in millis */ -// -// long addAtomicReaderCount(long toAdd); -// - + // + // @Group(1) + // long getReaderCount(); + // + // void setReaderCount(long rc); /* time in millis */ + // + // long addAtomicReaderCount(long toAdd); + // } diff --git a/src/test/java/net/openhft/chronicle/map/fromdocs/acid/revelations/DirtyReadIntolerant.java b/src/test/java/net/openhft/chronicle/map/fromdocs/acid/revelations/DirtyReadIntolerant.java index 4e5e16b45..8c503c387 100644 --- a/src/test/java/net/openhft/chronicle/map/fromdocs/acid/revelations/DirtyReadIntolerant.java +++ b/src/test/java/net/openhft/chronicle/map/fromdocs/acid/revelations/DirtyReadIntolerant.java @@ -24,10 +24,9 @@ public static void main(String[] args) { args[3] + "OPERAND_CHRONICLE_MAP" ); - Double coupon = 0.00; + double coupon = 0.00; BondVOInterface bond = newNativeReference(BondVOInterface.class); //BondVOInterface cslMock = newNativeReference(BondVOInterface.class); //mock'd - long stamp = 0; System.out.println( " ,,@t=" + System.currentTimeMillis() + " DirtyReadIntolerant ENTERING offHeapLock.readLock()" @@ -42,8 +41,9 @@ public static void main(String[] args) { " DirtyReadIntolerant sleeping " + sleepMock + " seconds" ); Thread.sleep(sleepMock * 1_000); + long stamp = 0; while ((stamp = offHeapLock.readLock()) < 0) { - ; // none + // none } System.out.println( " ,,@t=" + System.currentTimeMillis() + diff --git a/src/test/java/net/openhft/chronicle/map/fromdocs/acid/revelations/DirtyReadOffender.java b/src/test/java/net/openhft/chronicle/map/fromdocs/acid/revelations/DirtyReadOffender.java index af5d70381..184be4370 100644 --- a/src/test/java/net/openhft/chronicle/map/fromdocs/acid/revelations/DirtyReadOffender.java +++ b/src/test/java/net/openhft/chronicle/map/fromdocs/acid/revelations/DirtyReadOffender.java @@ -30,7 +30,7 @@ public static void main(String[] args) { " @t=" + System.currentTimeMillis() + " DirtyReadOffender established chm " ); - StampedLock offHeapLock = new ChronicleStampedLock( + final StampedLock offHeapLock = new ChronicleStampedLock( args[3] + "OPERAND_ChronicleStampedLock" ); @@ -60,7 +60,7 @@ public static void main(String[] args) { " DirtyReadOffender ACQUIRING offHeapLock.writeLock();" ); while ((stamp = offHeapLock.writeLock()) == 0) { - ; // none + // none } System.out.println( " @t=" + System.currentTimeMillis() + diff --git a/src/test/java/net/openhft/chronicle/map/fromdocs/acid/revelations/DirtyReadTolerance.java b/src/test/java/net/openhft/chronicle/map/fromdocs/acid/revelations/DirtyReadTolerance.java index de177dbc4..549152f8a 100644 --- a/src/test/java/net/openhft/chronicle/map/fromdocs/acid/revelations/DirtyReadTolerance.java +++ b/src/test/java/net/openhft/chronicle/map/fromdocs/acid/revelations/DirtyReadTolerance.java @@ -30,10 +30,8 @@ static ChronicleMap offHeap(String operand) throws IOEx .entries(16) .averageKeySize("123456789".length()) .createPersistedTo( - new File( - operand - // "C:\\Users\\buddy\\dev\\shm\\OPERAND_CHRONICLE_MAP" - ) + // "C:\\Users\\buddy\\dev\\shm\\OPERAND_CHRONICLE_MAP" + new File(operand) ); //.create(); } diff --git a/src/test/java/net/openhft/chronicle/map/fromdocs/acid/revelations/DirtyReadVictim.java b/src/test/java/net/openhft/chronicle/map/fromdocs/acid/revelations/DirtyReadVictim.java index 95f82e8a0..017b58a82 100644 --- a/src/test/java/net/openhft/chronicle/map/fromdocs/acid/revelations/DirtyReadVictim.java +++ b/src/test/java/net/openhft/chronicle/map/fromdocs/acid/revelations/DirtyReadVictim.java @@ -25,10 +25,9 @@ public static void main(String[] args) { args[3] + "OPERAND_CHRONICLE_MAP" ); - Double coupon = 0.00; + double coupon = 0.00; BondVOInterface bond = newNativeReference(BondVOInterface.class); //BondVOInterface cslMock = newNativeReference(BondVOInterface.class); //mock'd - long stamp = 0; System.out.println( " ,,@t=" + System.currentTimeMillis() + " DirtyReadVictim ENTERING offHeapLock.tryOptimisticRead()" @@ -44,6 +43,7 @@ public static void main(String[] args) { ); Thread.sleep(sleepMock * 1_000); + long stamp = 0; while ((stamp = offHeapLock.tryOptimisticRead()) < 0) { System.out.println( " ,,@t=" + System.currentTimeMillis() + diff --git a/src/test/java/net/openhft/chronicle/map/fromdocs/acid/revelations/DirtyReadVictimTest.java b/src/test/java/net/openhft/chronicle/map/fromdocs/acid/revelations/DirtyReadVictimTest.java index 143cce120..e8c65f3f3 100644 --- a/src/test/java/net/openhft/chronicle/map/fromdocs/acid/revelations/DirtyReadVictimTest.java +++ b/src/test/java/net/openhft/chronicle/map/fromdocs/acid/revelations/DirtyReadVictimTest.java @@ -17,11 +17,11 @@ public class DirtyReadVictimTest { @Before - public void setUp() throws Exception { + public void setUp() { } @After - public void tearDown() throws Exception { + public void tearDown() { } @Test @@ -33,9 +33,8 @@ public void main() { ChronicleMap chm = DirtyReadTolerance.offHeap( OS.getTarget() + "/OPERAND_CHRONICLE_MAP" -/* "C:\\Users\\buddy\\dev\\shm\\OPERAND_CHRONICLE_MAP"*/ ); - Double coupon = 0.00; + double coupon = 0.00; BondVOInterface bond = newNativeReference(BondVOInterface.class); long stamp = 0; System.out.println( @@ -44,10 +43,9 @@ public void main() { ); ChronicleStampedLock offHeapLock = new ChronicleStampedLock( OS.getTarget() + "/OPERAND_ChronicleStampedLock" - /*"C:\\Users\\buddy\\dev\\shm\\OPERAND_ChronicleStampedLock"*/ ); while ((stamp = offHeapLock.tryOptimisticRead()) == 0) { - ; // none + // none } System.out.println( " ,,@t=" + System.currentTimeMillis() + @@ -80,8 +78,8 @@ public void main() { ); // THIS Test will pass when ChronicleStampedLock is GA Assert.assertEquals( - offHeapLock.chmW.get("WriterCount ").getVolatileValue(), - 0L + 0L, + offHeapLock.chmW.get("WriterCount ").getVolatileValue() ); } else { System.out.println( diff --git a/src/test/java/net/openhft/chronicle/map/fromdocs/pingpong_latency/PingPongAddLeft.java b/src/test/java/net/openhft/chronicle/map/fromdocs/pingpong_latency/PingPongAddLeft.java index a4dd606b3..f2d8088d5 100644 --- a/src/test/java/net/openhft/chronicle/map/fromdocs/pingpong_latency/PingPongAddLeft.java +++ b/src/test/java/net/openhft/chronicle/map/fromdocs/pingpong_latency/PingPongAddLeft.java @@ -40,12 +40,12 @@ static void playPingPong(ChronicleMap chm, double add, long[] timings = new long[runs]; for (int j = 0; j < 100; j++) { for (int i = 0; i < runs; i++) { - long _start = System.nanoTime(); + final long startTime = System.nanoTime(); bond1.addAtomicCoupon(add); bond2.addAtomicCoupon(add); bond3.addAtomicCoupon(add); bond4.addAtomicCoupon(add); - timings[i] = (System.nanoTime() - _start - timeToCallNanoTime) / 4; + timings[i] = (System.nanoTime() - startTime - timeToCallNanoTime) / 4; } Arrays.sort(timings); System.out.printf("#%d: atomic add coupon 50/90/99%%tile was %,d / %,d / %,d%n", diff --git a/src/test/java/net/openhft/chronicle/map/fromdocs/pingpong_latency/PingPongCASLeft.java b/src/test/java/net/openhft/chronicle/map/fromdocs/pingpong_latency/PingPongCASLeft.java index 9abfe87af..eac19a664 100644 --- a/src/test/java/net/openhft/chronicle/map/fromdocs/pingpong_latency/PingPongCASLeft.java +++ b/src/test/java/net/openhft/chronicle/map/fromdocs/pingpong_latency/PingPongCASLeft.java @@ -35,8 +35,8 @@ public static void main(String... ignored) throws IOException { playPingPong(chm, 4, 5, true, "PingPongCASLEFT"); } - static void playPingPong(ChronicleMap chm, double _coupon, - double _coupon2, boolean setFirst, final String desc) { + static void playPingPong(ChronicleMap chm, double coupon, + double coupon2, boolean setFirst, final String desc) { BondVOInterface bond1 = newNativeReference(BondVOInterface.class); BondVOInterface bond2 = newNativeReference(BondVOInterface.class); BondVOInterface bond3 = newNativeReference(BondVOInterface.class); @@ -48,23 +48,23 @@ static void playPingPong(ChronicleMap chm, double _coup chm.acquireUsing("369604104", bond4); System.out.printf("\n\n" + desc + ": Timing 1 x off-heap operations on /dev/chm/RDR_DIM_Mock\n"); if (setFirst) { - bond1.setCoupon(_coupon); - bond2.setCoupon(_coupon); - bond3.setCoupon(_coupon); - bond4.setCoupon(_coupon); + bond1.setCoupon(coupon); + bond2.setCoupon(coupon); + bond3.setCoupon(coupon); + bond4.setCoupon(coupon); } int timeToCallNanoTime = 30; int runs = 1000000; long[] timings = new long[runs]; for (int j = 0; j < 10; j++) { for (int i = 0; i < runs; i++) { - long _start = System.nanoTime(); // - while (!bond1.compareAndSwapCoupon(_coupon, _coupon2)) ; - while (!bond2.compareAndSwapCoupon(_coupon, _coupon2)) ; - while (!bond3.compareAndSwapCoupon(_coupon, _coupon2)) ; - while (!bond4.compareAndSwapCoupon(_coupon, _coupon2)) ; + final long start = System.nanoTime(); // + while (!bond1.compareAndSwapCoupon(coupon, coupon2)) ; + while (!bond2.compareAndSwapCoupon(coupon, coupon2)) ; + while (!bond3.compareAndSwapCoupon(coupon, coupon2)) ; + while (!bond4.compareAndSwapCoupon(coupon, coupon2)) ; - timings[i] = (System.nanoTime() - _start - timeToCallNanoTime) / 4; + timings[i] = (System.nanoTime() - start - timeToCallNanoTime) / 4; } Arrays.sort(timings); System.out.printf("#%d: compareAndSwapCoupon() 50/90/99%%tile was %,d / %,d / %,d%n", @@ -72,7 +72,7 @@ static void playPingPong(ChronicleMap chm, double _coup } } - static ChronicleMap acquireCHM() throws IOException { + static ChronicleMap acquireCHM() { // ensure thread ids are globally unique. Affinity.setThreadId(); return ChronicleMapBuilder.of(String.class, BondVOInterface.class) diff --git a/src/test/java/net/openhft/chronicle/map/fromdocs/pingpong_latency/PingPongLockRight.java b/src/test/java/net/openhft/chronicle/map/fromdocs/pingpong_latency/PingPongLockRight.java index 92a652cfb..082ed906f 100644 --- a/src/test/java/net/openhft/chronicle/map/fromdocs/pingpong_latency/PingPongLockRight.java +++ b/src/test/java/net/openhft/chronicle/map/fromdocs/pingpong_latency/PingPongLockRight.java @@ -9,7 +9,7 @@ import java.io.IOException; public class PingPongLockRight { - public static void main(String... ignored) throws IOException, InterruptedException { + public static void main(String... ignored) throws IOException { ChronicleMap chm = PingPongCASLeft.acquireCHM(); //PingPongLockLeft.playPingPong(chm, 5, 4, false, "PingPongLockRIGHT"); diff --git a/src/test/java/net/openhft/chronicle/map/ipc/StateMachineData.java b/src/test/java/net/openhft/chronicle/map/ipc/StateMachineData.java index 8e90f02a5..916546532 100644 --- a/src/test/java/net/openhft/chronicle/map/ipc/StateMachineData.java +++ b/src/test/java/net/openhft/chronicle/map/ipc/StateMachineData.java @@ -6,7 +6,6 @@ import net.openhft.chronicle.bytes.Byteable; import net.openhft.chronicle.bytes.BytesStore; -import java.io.IOException; import java.nio.channels.FileLock; /** @@ -141,12 +140,12 @@ public long maxSize() { } @Override - public FileLock lock(boolean shared) throws IOException { + public FileLock lock(boolean shared) { throw new UnsupportedOperationException(); } @Override - public FileLock tryLock(boolean shared) throws IOException { + public FileLock tryLock(boolean shared) { throw new UnsupportedOperationException(); } } diff --git a/src/test/java/net/openhft/chronicle/map/ipc/StateMachineState.java b/src/test/java/net/openhft/chronicle/map/ipc/StateMachineState.java index 89388aad2..5b36b8cef 100644 --- a/src/test/java/net/openhft/chronicle/map/ipc/StateMachineState.java +++ b/src/test/java/net/openhft/chronicle/map/ipc/StateMachineState.java @@ -17,7 +17,7 @@ public enum StateMachineState { STATE_3(30), STATE_3_WORKING(31); - private int state; + private final int state; /** * c-tor diff --git a/src/test/java/net/openhft/chronicle/map/ipc/StateMachineTutorial.java b/src/test/java/net/openhft/chronicle/map/ipc/StateMachineTutorial.java index 6608b43e6..045c4837a 100644 --- a/src/test/java/net/openhft/chronicle/map/ipc/StateMachineTutorial.java +++ b/src/test/java/net/openhft/chronicle/map/ipc/StateMachineTutorial.java @@ -32,14 +32,14 @@ public static void main(String[] args) { StateMachineState st = smd.getState(); if (st == StateMachineState.STATE_0) { - long start = System.nanoTime(); + final long start = System.nanoTime(); //fire the first state change smd.setStateData(0); smd.setState(StateMachineState.STATE_0, StateMachineState.STATE_1); while (!smd.done()) { - // busy wait + Thread.yield(); } long end = System.nanoTime(); diff --git a/src/test/java/net/openhft/chronicle/map/issue/Issue423LockFileRemainsLockedOnWindowsIfBuilderThrowsTest.java b/src/test/java/net/openhft/chronicle/map/issue/Issue423LockFileRemainsLockedOnWindowsIfBuilderThrowsTest.java index 397016408..164b74610 100644 --- a/src/test/java/net/openhft/chronicle/map/issue/Issue423LockFileRemainsLockedOnWindowsIfBuilderThrowsTest.java +++ b/src/test/java/net/openhft/chronicle/map/issue/Issue423LockFileRemainsLockedOnWindowsIfBuilderThrowsTest.java @@ -34,7 +34,7 @@ public void reproduce() throws IOException { } try (RandomAccessFile raf = CanonicalRandomAccessFiles.acquire(file.getCanonicalFile()); - FileChannel fileChannel = raf.getChannel();) { + FileChannel fileChannel = raf.getChannel()) { try (FileLock lock = fileChannel.tryLock()) { // Make sure we can lock (hence the file was not previously locked) diff --git a/src/test/java/net/openhft/chronicle/map/issue/ParallelStartupTest.java b/src/test/java/net/openhft/chronicle/map/issue/ParallelStartupTest.java index bb131fceb..ec1002006 100644 --- a/src/test/java/net/openhft/chronicle/map/issue/ParallelStartupTest.java +++ b/src/test/java/net/openhft/chronicle/map/issue/ParallelStartupTest.java @@ -6,19 +6,17 @@ import net.openhft.chronicle.core.io.IOTools; import net.openhft.chronicle.map.ChronicleMap; import net.openhft.chronicle.map.ChronicleMapBuilder; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.RepeatedTest; import java.io.File; import java.io.IOException; import java.util.concurrent.atomic.AtomicInteger; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - public class ParallelStartupTest { @RepeatedTest(5) - public void test() throws InterruptedException { + public void test() { try { final File file = IOTools.createTempFile("issue342"); Thread[] thread = new Thread[16]; @@ -44,16 +42,14 @@ public void test() throws InterruptedException { }); } - for (int i = 0; i < thread.length; i++) - thread[i].start(); + for (Thread item : thread) item.start(); - for (int i = 0; i < thread.length; i++) - thread[i].join(); + for (Thread value : thread) value.join(); - assertEquals(thread.length, succ.get()); + Assertions.assertEquals(thread.length, succ.get()); } catch (Exception ex) { ex.printStackTrace(); - fail(); + Assertions.fail(); } } diff --git a/src/test/java/net/openhft/chronicle/map/issue/PutIfAbsentNoGarbageTest.java b/src/test/java/net/openhft/chronicle/map/issue/PutIfAbsentNoGarbageTest.java index 969ff9db7..f5bf40dcb 100644 --- a/src/test/java/net/openhft/chronicle/map/issue/PutIfAbsentNoGarbageTest.java +++ b/src/test/java/net/openhft/chronicle/map/issue/PutIfAbsentNoGarbageTest.java @@ -9,17 +9,15 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.io.IOException; - public class PutIfAbsentNoGarbageTest { - static ChronicleMap newShmLongLongValueUsing(int size, boolean putIfAbsentUsingValue) throws IOException { + static ChronicleMap newShmLongLongValueUsing(int size, boolean putIfAbsentUsingValue) { return ChronicleMapBuilder.simpleMapOf(Long.class, LongValue.class) .entries(size).putIfAbsentUsingValue(putIfAbsentUsingValue).create(); } @Test - public void testPutIfAbsentUsingValue() throws IOException, Throwable { + public void testPutIfAbsentUsingValue() throws Throwable { try (ChronicleMap map = newShmLongLongValueUsing(10, true)) { Long k = 1L; @@ -41,7 +39,7 @@ public void testPutIfAbsentUsingValue() throws IOException, Throwable { } @Test - public void testPutIfAbsentDefault() throws IOException, Throwable { + public void testPutIfAbsentDefault() throws Throwable { try (ChronicleMap map = newShmLongLongValueUsing(10, false)) { Long k = 1L; diff --git a/src/test/java/net/openhft/chronicle/map/jsr166/JSR166TestCase.java b/src/test/java/net/openhft/chronicle/map/jsr166/JSR166TestCase.java index 1c5bae917..d5530df74 100644 --- a/src/test/java/net/openhft/chronicle/map/jsr166/JSR166TestCase.java +++ b/src/test/java/net/openhft/chronicle/map/jsr166/JSR166TestCase.java @@ -5,15 +5,10 @@ import junit.framework.AssertionFailedError; import net.openhft.chronicle.core.Jvm; -import org.jetbrains.annotations.NotNull; import org.junit.After; import org.junit.Assert; import org.junit.Before; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; import java.security.*; import java.util.*; import java.util.concurrent.*; @@ -90,23 +85,23 @@ public class JSR166TestCase { * The number of elements to place in collections, arrays, etc. */ public static final int SIZE = 20; - public static final Integer zero = new Integer(0); - public static final Integer one = new Integer(1); - public static final Integer two = new Integer(2); - public static final Integer three = new Integer(3); - public static final Integer four = new Integer(4); - public static final Integer five = new Integer(5); - public static final Integer six = new Integer(6); - public static final Integer seven = new Integer(7); - public static final Integer eight = new Integer(8); - public static final Integer nine = new Integer(9); - public static final Integer m1 = new Integer(-1); - public static final Integer m2 = new Integer(-2); - public static final Integer m3 = new Integer(-3); - public static final Integer m4 = new Integer(-4); - public static final Integer m5 = new Integer(-5); - public static final Integer m6 = new Integer(-6); - public static final Integer m10 = new Integer(-10); + public static final Integer zero = 0; + public static final Integer one = 1; + public static final Integer two = 2; + public static final Integer three = 3; + public static final Integer four = 4; + public static final Integer five = 5; + public static final Integer six = 6; + public static final Integer seven = 7; + public static final Integer eight = 8; + public static final Integer nine = 9; + public static final Integer m1 = -1; + public static final Integer m2 = -2; + public static final Integer m3 = -3; + public static final Integer m4 = -4; + public static final Integer m5 = -5; + public static final Integer m6 = -6; + public static final Integer m10 = -10; public static final Integer notPresent = 42; public static final String TEST_STRING = "a test string"; protected static final boolean expensiveTests = false; @@ -125,7 +120,7 @@ public class JSR166TestCase { * if the sleep is shorter than specified, may re-sleep or yield * until time elapses. */ - static void delay(long millis) throws InterruptedException { + static void delay(long millis) { long startTime = System.nanoTime(); long ns = millis * 1000 * 1000; for (; ; ) { @@ -145,9 +140,9 @@ static void delay(long millis) throws InterruptedException { * Returns a policy containing all the permissions we ever need. */ public static Policy permissivePolicy() { - return new AdjustablePolicy + return new AdjustablePolicy( // Permissions j.u.c. needs directly - (new RuntimePermission("modifyThread"), + new RuntimePermission("modifyThread"), new RuntimePermission("getClassLoader"), new RuntimePermission("setContextClassLoader"), // Permissions needed to change permissions! @@ -169,11 +164,8 @@ public boolean isDone() { } public void run() { - try { - delay(timeoutMillis); - done = true; - } catch (InterruptedException ok) { - } + delay(timeoutMillis); + done = true; } }; } @@ -278,9 +270,7 @@ void checkForkJoinPoolThreadLeaks() throws InterruptedException { thread.join(LONG_DELAY_MS); if (!thread.isAlive()) continue; thread.stop(); - throw new AssertionFailedError - (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n", - toString(), name)); + throw new AssertionFailedError(String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n", this, name)); } } } @@ -446,13 +436,9 @@ protected void assertThreadStaysAlive(Thread thread) { * Checks that thread does not terminate within the given millisecond delay. */ void assertThreadStaysAlive(Thread thread, long millis) { - try { - // No need to optimize the Assert.failing case via Thread.join. - delay(millis); - Assert.assertTrue(thread.isAlive()); - } catch (InterruptedException ie) { - Assert.fail("Unexpected InterruptedException"); - } + // No need to optimize the Assert.failing case via Thread.join. + delay(millis); + Assert.assertTrue(thread.isAlive()); } /** @@ -467,14 +453,10 @@ void assertThreadsStayAlive(Thread... threads) { * Checks that the threads do not terminate within the given millisecond delay. */ void assertThreadsStayAlive(long millis, Thread... threads) { - try { - // No need to optimize the Assert.failing case via Thread.join. - delay(millis); - for (Thread thread : threads) - Assert.assertTrue(thread.isAlive()); - } catch (InterruptedException ie) { - Assert.fail("Unexpected InterruptedException"); - } + // No need to optimize the Assert.failing case via Thread.join. + delay(millis); + for (Thread thread : threads) + Assert.assertTrue(thread.isAlive()); } /** @@ -492,8 +474,9 @@ void assertFutureTimesOut(Future future, long timeoutMillis) { long startTime = System.nanoTime(); try { future.get(timeoutMillis, MILLISECONDS); - shouldThrow(); + assertThrows(); } catch (TimeoutException success) { + Assert.assertNotNull(success); } catch (Exception e) { threadUnexpectedException(e); } finally { @@ -505,17 +488,9 @@ void assertFutureTimesOut(Future future, long timeoutMillis) { /** * Fails with message "should throw exception". */ - public void shouldThrow() { + public void assertThrows() { Assert.fail("Should throw exception"); } - - /** - * Fails with message "should throw " + exceptionName. - */ - public void shouldThrow(String exceptionName) { - Assert.fail("Should throw " + exceptionName); - } - /** * android-changed * Android does not use a SecurityManager. This will simply execute @@ -525,38 +500,6 @@ public void runWithPermissions(Runnable r, Permission... permissions) { r.run(); } - /** - * android-changed - * Android does not use a SecurityManager. This will simply execute - * the runnable ignoring permissions. - */ - public void runWithSecurityManagerWithPermissions(Runnable r, - Permission... permissions) { - r.run(); - } - - /** - * Runs a runnable without any permissions. - */ - public void runWithoutPermissions(Runnable r) { - runWithPermissions(r); - } - - /** - * Sleeps until the given time has elapsed. - * Throws AssertionFailedError if interrupted. - */ - void sleep(long millis) { - try { - delay(millis); - } catch (InterruptedException ie) { - AssertionFailedError afe = - new AssertionFailedError("Unexpected InterruptedException"); - afe.initCause(ie); - throw afe; - } - } - /** * Spin-waits up to the specified number of milliseconds for the given * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING. @@ -579,14 +522,6 @@ else if (millisElapsedSince(startTime) > timeoutMillis) { } } - /** - * Waits up to LONG_DELAY_MS for the given thread to enter a wait - * state: BLOCKED, WAITING, or TIMED_WAITING. - */ - void waitForThreadToEnterWaitState(Thread thread) { - waitForThreadToEnterWaitState(thread, LONG_DELAY_MS); - } - /** * Returns the number of milliseconds since time given by * startNanoTime, which must have been previously returned from a @@ -596,180 +531,7 @@ protected long millisElapsedSince(long startNanoTime) { return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime); } - /** - * Returns a new started daemon Thread running the given runnable. - */ - protected Thread newStartedThread(Runnable runnable) { - Thread t = new Thread(runnable); - t.setDaemon(true); - t.start(); - return t; - } - - /** - * Waits for the specified time (in milliseconds) for the thread - * to terminate (using {@link Thread#join(long)}), else interrupts - * the thread (in the hope that it may terminate later) and Assert.fails. - */ - protected void awaitTermination(Thread t, long timeoutMillis) { - try { - t.join(timeoutMillis); - } catch (InterruptedException ie) { - threadUnexpectedException(ie); - } finally { - if (t.getState() != Thread.State.TERMINATED) { - t.interrupt(); - Assert.fail("Test timed out"); - } - } - } - // Some convenient Runnable classes - - /** - * Waits for LONG_DELAY_MS milliseconds for the thread to - * terminate (using {@link Thread#join(long)}), else interrupts - * the thread (in the hope that it may terminate later) and Assert.fails. - */ - protected void awaitTermination(Thread t) { - awaitTermination(t, LONG_DELAY_MS); - } - - public Callable latchAwaitingStringTask(final CountDownLatch latch) { - return new CheckedCallable() { - protected String realCall() { - try { - latch.await(); - } catch (InterruptedException quittingTime) { - } - return TEST_STRING; - } - }; - } - - public Runnable awaiter(final CountDownLatch latch) { - return new CheckedRunnable() { - public void realRun() throws InterruptedException { - await(latch); - } - }; - } - - public void await(CountDownLatch latch) { - try { - Assert.assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS)); - } catch (Throwable t) { - threadUnexpectedException(t); - } - } - - public void await(Semaphore semaphore) { - try { - Assert.assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS)); - } catch (Throwable t) { - threadUnexpectedException(t); - } - } - - public Runnable possiblyInterruptedRunnable(final long timeoutMillis) { - return new CheckedRunnable() { - protected void realRun() { - try { - delay(timeoutMillis); - } catch (InterruptedException ok) { - } - } - }; - } - - protected void checkEmpty(BlockingQueue q) { - try { - Assert.assertTrue(q.isEmpty()); - Assert.assertEquals(0, q.size()); - Assert.assertNull(q.peek()); - Assert.assertNull(q.poll()); - Assert.assertNull(q.poll(0, MILLISECONDS)); - Assert.assertEquals(q.toString(), "[]"); - Assert.assertTrue(Arrays.equals(q.toArray(), new Object[0])); - Assert.assertFalse(q.iterator().hasNext()); - try { - q.element(); - shouldThrow(); - } catch (NoSuchElementException success) { - } - try { - q.iterator().next(); - shouldThrow(); - } catch (NoSuchElementException success) { - } - try { - q.remove(); - shouldThrow(); - } catch (NoSuchElementException success) { - } - } catch (InterruptedException ie) { - threadUnexpectedException(ie); - } - } - - void assertSerialEquals(Object x, Object y) { - Assert.assertTrue(Arrays.equals(serialBytes(x), serialBytes(y))); - } - - void assertNotSerialEquals(Object x, Object y) { - Assert.assertFalse(Arrays.equals(serialBytes(x), serialBytes(y))); - } - - byte[] serialBytes(Object o) { - try { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - ObjectOutputStream oos = new ObjectOutputStream(bos); - oos.writeObject(o); - oos.flush(); - oos.close(); - return bos.toByteArray(); - } catch (Throwable t) { - threadUnexpectedException(t); - return new byte[0]; - } - } - - @SuppressWarnings("unchecked") - protected T serialClone(T o) { - try { - ObjectInputStream ois = new ObjectInputStream - (new ByteArrayInputStream(serialBytes(o))); - T clone = (T) ois.readObject(); - Assert.assertSame(o.getClass(), clone.getClass()); - return clone; - } catch (Throwable t) { - threadUnexpectedException(t); - return null; - } - } - - public void assertThrows(Class expectedExceptionClass, - Runnable... throwingActions) { - for (Runnable throwingAction : throwingActions) { - boolean threw = false; - try { - throwingAction.run(); - } catch (Throwable t) { - threw = true; - if (!expectedExceptionClass.isInstance(t)) { - AssertionFailedError afe = - new AssertionFailedError - ("Expected " + expectedExceptionClass.getName() + - ", got " + t.getClass().getName()); - afe.initCause(t); - threadUnexpectedException(afe); - } - } - if (!threw) - shouldThrow(expectedExceptionClass.getName()); - } - } - public interface TrackedRunnable extends Runnable { boolean isDone(); } @@ -816,357 +578,4 @@ public String toString() { return "AdjustablePolicy with permissions " + ps; } } - -// /** -// * Spin-waits up to LONG_DELAY_MS until flag becomes true. -// */ -// public void await(AtomicBoolean flag) { -// await(flag, LONG_DELAY_MS); -// } - -// /** -// * Spin-waits up to the specified timeout until flag becomes true. -// */ -// public void await(AtomicBoolean flag, long timeoutMillis) { -// long startTime = System.nanoTime(); -// while (!flag.get()) { -// if (millisElapsedSince(startTime) > timeoutMillis) -// throw new AssertionFailedError("timed out"); -// Thread.yield(); -// } -// } - - public static class NoOpRunnable implements Runnable { - public void run() { - } - } - - public static class NoOpCallable implements Callable { - public Object call() { - return Boolean.TRUE; - } - } - - public static class StringTask implements Callable { - public String call() { - return TEST_STRING; - } - } - - public static class NPETask implements Callable { - public String call() { - throw new NullPointerException(); - } - } - - public static class CallableOne implements Callable { - public Integer call() { - return one; - } - } - - /** - * For use as ThreadFactory in constructors - */ - public static class SimpleThreadFactory implements ThreadFactory { - public Thread newThread(@NotNull Runnable r) { - return new Thread(r); - } - } - - public static class TrackedShortRunnable implements Runnable { - public volatile boolean done = false; - - public void run() { - try { - delay(SHORT_DELAY_MS); - done = true; - } catch (InterruptedException ok) { - } - } - } - - public static class TrackedSmallRunnable implements Runnable { - public volatile boolean done = false; - - public void run() { - try { - delay(SMALL_DELAY_MS); - done = true; - } catch (InterruptedException ok) { - } - } - } - - public static class TrackedMediumRunnable implements Runnable { - public volatile boolean done = false; - - public void run() { - try { - delay(MEDIUM_DELAY_MS); - done = true; - } catch (InterruptedException ok) { - } - } - } - - public static class TrackedLongRunnable implements Runnable { - public volatile boolean done = false; - - public void run() { - try { - delay(LONG_DELAY_MS); - done = true; - } catch (InterruptedException ok) { - } - } - } - - public static class TrackedNoOpRunnable implements Runnable { - public volatile boolean done = false; - - public void run() { - done = true; - } - } - - public static class TrackedCallable implements Callable { - public volatile boolean done = false; - - public Object call() { - try { - delay(SMALL_DELAY_MS); - done = true; - } catch (InterruptedException ok) { - } - return Boolean.TRUE; - } - } - - /** - * For use as RejectedExecutionHandler in constructors - */ - public static class NoOpREHandler implements RejectedExecutionHandler { - public void rejectedExecution(Runnable r, - ThreadPoolExecutor executor) { - } - } - - public abstract class CheckedRunnable implements Runnable { - protected abstract void realRun() throws Throwable; - - public final void run() { - try { - realRun(); - } catch (Throwable t) { - threadUnexpectedException(t); - } - } - } - - public abstract class RunnableShouldThrow implements Runnable { - final Class exceptionClass; - - RunnableShouldThrow(Class exceptionClass) { - this.exceptionClass = exceptionClass; - } - - protected abstract void realRun() throws Throwable; - - public final void run() { - try { - realRun(); - threadShouldThrow(exceptionClass.getSimpleName()); - } catch (Throwable t) { - if (!exceptionClass.isInstance(t)) - threadUnexpectedException(t); - } - } - } - - public abstract class ThreadShouldThrow extends Thread { - final Class exceptionClass; - - ThreadShouldThrow(Class exceptionClass) { - this.exceptionClass = exceptionClass; - } - - protected abstract void realRun() throws Throwable; - - public final void run() { - try { - realRun(); - threadShouldThrow(exceptionClass.getSimpleName()); - } catch (Throwable t) { - if (!exceptionClass.isInstance(t)) - threadUnexpectedException(t); - } - } - } - - public abstract class CheckedInterruptedRunnable implements Runnable { - protected abstract void realRun() throws Throwable; - - public final void run() { - try { - realRun(); - threadShouldThrow("InterruptedException"); - } catch (InterruptedException success) { - threadAssertFalse(Thread.interrupted()); - } catch (Throwable t) { - threadUnexpectedException(t); - } - } - } - - public abstract class CheckedCallable implements Callable { - protected abstract T realCall() throws Throwable; - - public final T call() { - try { - return realCall(); - } catch (Throwable t) { - threadUnexpectedException(t); - return null; - } - } - } - - public abstract class CheckedInterruptedCallable - implements Callable { - protected abstract T realCall() throws Throwable; - - public final T call() { - try { - T result = realCall(); - threadShouldThrow("InterruptedException"); - return result; - } catch (InterruptedException success) { - threadAssertFalse(Thread.interrupted()); - } catch (Throwable t) { - threadUnexpectedException(t); - } - return null; - } - } - - public class ShortRunnable extends CheckedRunnable { - protected void realRun() throws Throwable { - delay(SHORT_DELAY_MS); - } - } - - public class ShortInterruptedRunnable extends CheckedInterruptedRunnable { - protected void realRun() throws InterruptedException { - delay(SHORT_DELAY_MS); - } - } - - public class SmallRunnable extends CheckedRunnable { - protected void realRun() throws Throwable { - delay(SMALL_DELAY_MS); - } - } - - public class SmallPossiblyInterruptedRunnable extends CheckedRunnable { - protected void realRun() { - try { - delay(SMALL_DELAY_MS); - } catch (InterruptedException ok) { - } - } - } - - public class SmallCallable extends CheckedCallable { - protected Object realCall() throws InterruptedException { - delay(SMALL_DELAY_MS); - return Boolean.TRUE; - } - } - - public class MediumRunnable extends CheckedRunnable { - protected void realRun() throws Throwable { - delay(MEDIUM_DELAY_MS); - } - } - - public class MediumInterruptedRunnable extends CheckedInterruptedRunnable { - protected void realRun() throws InterruptedException { - delay(MEDIUM_DELAY_MS); - } - } - - public class MediumPossiblyInterruptedRunnable extends CheckedRunnable { - protected void realRun() { - try { - delay(MEDIUM_DELAY_MS); - } catch (InterruptedException ok) { - } - } - } - - public class LongPossiblyInterruptedRunnable extends CheckedRunnable { - protected void realRun() { - try { - delay(LONG_DELAY_MS); - } catch (InterruptedException ok) { - } - } - } - - /** - * Analog of CheckedRunnable for RecursiveAction - */ - public abstract class CheckedRecursiveAction extends RecursiveAction { - protected abstract void realCompute() throws Throwable; - - @Override - protected final void compute() { - try { - realCompute(); - } catch (Throwable t) { - threadUnexpectedException(t); - } - } - } - - /** - * Analog of CheckedCallable for RecursiveTask - */ - public abstract class CheckedRecursiveTask extends RecursiveTask { - protected abstract T realCompute() throws Throwable; - - @Override - protected final T compute() { - try { - return realCompute(); - } catch (Throwable t) { - threadUnexpectedException(t); - return null; - } - } - } - - /** - * A CyclicBarrier that uses timed await and Assert.fails with - * AssertionFailedErrors instead of throwing checked exceptions. - */ - public class CheckedBarrier extends CyclicBarrier { - public CheckedBarrier(int parties) { - super(parties); - } - - public int await() { - try { - return super.await(2 * LONG_DELAY_MS, MILLISECONDS); - } catch (TimeoutException e) { - throw new AssertionFailedError("timed out"); - } catch (Exception e) { - AssertionFailedError afe = - new AssertionFailedError("Unexpected exception: " + e); - afe.initCause(e); - throw afe; - } - } - } } diff --git a/src/test/java/net/openhft/chronicle/map/jsr166/map/ChronicleMapTest.java b/src/test/java/net/openhft/chronicle/map/jsr166/map/ChronicleMapTest.java index 466cc5f95..317aac602 100644 --- a/src/test/java/net/openhft/chronicle/map/jsr166/map/ChronicleMapTest.java +++ b/src/test/java/net/openhft/chronicle/map/jsr166/map/ChronicleMapTest.java @@ -26,13 +26,13 @@ @SuppressWarnings({"rawtypes", "unchecked", "try"}) public class ChronicleMapTest extends JSR166TestCase { - static ChronicleMap newShmIntString(int size) throws IOException { + static ChronicleMap newShmIntString(int size) { return ChronicleMapBuilder.of(Integer.class, CharSequence.class) .averageValueSize(1) .entries(size).create(); } - static ChronicleMap newStrStrMap(int size) throws IOException { + static ChronicleMap newStrStrMap(int size) { return ChronicleMapBuilder.of(CharSequence.class, CharSequence.class) .averageKeySize(20).averageValueSize(20) .entries(size).create(); @@ -215,9 +215,7 @@ public void testEntrySet() throws IOException { try (ChronicleMap map = map5()) { Set> s = map.entrySet(); assertEquals(5, s.size()); - Iterator> it = s.iterator(); - while (it.hasNext()) { - Entry e = it.next(); + for (Entry e : s) { assertTrue( (e.getKey().equals(one) && "A".contentEquals(e.getValue())) || (e.getKey().equals(two) && "B".contentEquals(e.getValue())) || @@ -309,8 +307,7 @@ public void testReplaceValue() throws * replace value succeeds when the given key mapped to expected value */ @Test(timeout = 5000) - public void testReplaceValue2 - () throws IOException { + public void testReplaceValue2() throws IOException { try (ChronicleMap map = map5()) { assertEquals("A", map.get(one).toString()); assertTrue(map.replace(one, "A", "Z")); @@ -331,22 +328,6 @@ public void testRemove() throws } } - /** - * remove(key,value) removes only if pair present - */ - @Test(timeout = 5000) - public void testRemove2 - () throws IOException { - /* try( ChronicleMap map = map5(8076)) { - map.remove(five, "E"); - assertEquals(4, map.size()); - assertFalse(map.containsKey(five)); - map.remove(four, "A"); - assertEquals(4, map.size()); - assertTrue(map.containsKey(four)); - */ - } - /** * size returns the correct values */ @@ -407,8 +388,9 @@ public void testGet_NullPointerException() throws IOException { try (ChronicleMap c = newShmIntString(8076)) { c.get(null); - shouldThrow(); + assertThrows(); } catch (NullPointerException | IllegalArgumentException success) { + Assert.assertNotNull(success); } } @@ -419,8 +401,9 @@ public void testGet_NullPointerException() throws IOException { public void testContainsKey_NullPointerException() throws IOException { try (ChronicleMap c = newShmIntString(8076)) { c.containsKey(null); - shouldThrow(); + assertThrows(); } catch (NullPointerException | IllegalArgumentException success) { + Assert.assertNotNull(success); } } @@ -431,8 +414,9 @@ public void testContainsKey_NullPointerException() throws IOException { public void testPut1_NullPointerException() throws IOException { try (ChronicleMap c = newShmIntString(8076)) { c.put(null, "whatever"); - shouldThrow(); + assertThrows(); } catch (NullPointerException | IllegalArgumentException success) { + Assert.assertNotNull(success); } } @@ -440,12 +424,12 @@ public void testPut1_NullPointerException() throws IOException { * put(x, null) throws NPE */ @Test(timeout = 5000) - public void testPut2_NullPointerException - () throws IOException { + public void testPut2_NullPointerException() throws IOException { try (ChronicleMap c = newShmIntString(8076)) { c.put(notPresent, null); - shouldThrow(); + assertThrows(); } catch (NullPointerException | IllegalArgumentException success) { + Assert.assertNotNull(success); } } @@ -453,12 +437,12 @@ public void testPut1_NullPointerException() throws IOException { * putIfAbsent(null, x) throws NPE */ @Test(timeout = 5000) - public void testPutIfAbsent1_NullPointerException - () throws IOException { + public void testPutIfAbsent1_NullPointerException() throws IOException { try (ChronicleMap c = newShmIntString(8076)) { c.putIfAbsent(null, "whatever"); - shouldThrow(); + assertThrows(); } catch (NullPointerException | IllegalArgumentException success) { + Assert.assertNotNull(success); } } @@ -466,12 +450,12 @@ public void testPut1_NullPointerException() throws IOException { * replace(null, x) throws NPE */ @Test(timeout = 5000) - public void testReplace_NullPointerException - () throws IOException { + public void testReplace_NullPointerException() throws IOException { try (ChronicleMap c = newShmIntString(8076)) { c.replace(null, "whatever"); - shouldThrow(); + assertThrows(); } catch (NullPointerException | IllegalArgumentException success) { + Assert.assertNotNull(success); } } @@ -479,12 +463,12 @@ public void testPut1_NullPointerException() throws IOException { * replace(null, x, y) throws NPE */ @Test(timeout = 5000) - public void testReplaceValue_NullPointerException - () throws IOException { + public void testReplaceValue_NullPointerException() throws IOException { try (ChronicleMap c = newShmIntString(8076)) { c.replace(null, "A", "whatever"); - shouldThrow(); + assertThrows(); } catch (NullPointerException | IllegalArgumentException success) { + Assert.assertNotNull(success); } } @@ -495,8 +479,9 @@ public void testPut1_NullPointerException() throws IOException { public void testPutIfAbsent2_NullPointerException() throws IOException { try (ChronicleMap c = newShmIntString(8076)) { c.putIfAbsent(notPresent, null); - shouldThrow(); + assertThrows(); } catch (NullPointerException | IllegalArgumentException success) { + Assert.assertNotNull(success); } } @@ -507,8 +492,9 @@ public void testPutIfAbsent2_NullPointerException() throws IOException { public void testReplace2_NullPointerException() throws IOException { try (ChronicleMap c = newShmIntString(8076)) { c.replace(notPresent, null); - shouldThrow(); + assertThrows(); } catch (NullPointerException | IllegalArgumentException success) { + Assert.assertNotNull(success); } } @@ -519,8 +505,9 @@ public void testReplace2_NullPointerException() throws IOException { public void testReplaceValue2_NullPointerException() throws IOException { try (ChronicleMap c = newShmIntString(8076)) { c.replace(notPresent, null, "A"); - shouldThrow(); + assertThrows(); } catch (NullPointerException | IllegalArgumentException success) { + Assert.assertNotNull(success); } } @@ -531,8 +518,9 @@ public void testReplaceValue2_NullPointerException() throws IOException { public void testReplaceValue3_NullPointerException() throws IOException { try (ChronicleMap c = newShmIntString(8076)) { c.replace(notPresent, "A", null); - shouldThrow(); + assertThrows(); } catch (NullPointerException | IllegalArgumentException success) { + Assert.assertNotNull(success); } } @@ -544,8 +532,9 @@ public void testRemove1_NullPointerException() throws IOException { try (ChronicleMap c = newStrStrMap(8076)) { c.put("sadsdf", "asdads"); c.remove(null); - shouldThrow(); + assertThrows(); } catch (NullPointerException | IllegalArgumentException success) { + Assert.assertNotNull(success); } } @@ -553,13 +542,13 @@ public void testRemove1_NullPointerException() throws IOException { * remove(null, x) throws NPE */ @Test(timeout = 5000) - public void testRemove2_NullPointerException - () throws IOException { + public void testRemove2_NullPointerException() throws IOException { try (ChronicleMap c = newStrStrMap(8086)) { c.put("sadsdf", "asdads"); c.remove(null, "whatever"); - shouldThrow(); + assertThrows(); } catch (NullPointerException | IllegalArgumentException success) { + Assert.assertNotNull(success); } } @@ -605,87 +594,4 @@ public void testPercentageComplete() { } } } - - // classes for testing Comparable fallbacks - static class BI implements Comparable { - private final int value; - - BI(int value) { - this.value = value; - } - - public int compareTo(BI other) { - return Integer.compare(value, other.value); - } - - public boolean equals(Object x) { - return (x instanceof BI) && ((BI) x).value == value; - } - - public int hashCode() { - return 42; - } - } - - static class CI extends BI { - CI(int value) { - super(value); - } - } - - static class DI extends BI { - DI(int value) { - super(value); - } - } - - static class BS implements Comparable { - private final String value; - - BS(String value) { - this.value = value; - } - - public int compareTo(BS other) { - return value.compareTo(other.value); - } - - public boolean equals(Object x) { - return (x instanceof BS) && value.equals(((BS) x).value); - } - - public int hashCode() { - return 42; - } - } - - static class LexicographicList> extends ArrayList - implements Comparable> { - private static final long serialVersionUID = 0; - static long total; - static long n; - - LexicographicList(Collection c) { - super(c); - } - - LexicographicList(E e) { - super(Collections.singleton(e)); - } - - public int compareTo(LexicographicList other) { - long start = System.currentTimeMillis(); - int common = Math.min(size(), other.size()); - int r = 0; - for (int i = 0; i < common; i++) { - if ((r = get(i).compareTo(other.get(i))) != 0) - break; - } - if (r == 0) - r = Integer.compare(size(), other.size()); - total += System.currentTimeMillis() - start; - n++; - return r; - } - } } diff --git a/src/test/java/net/openhft/chronicle/map/jsr166/map/LoopHelpers.java b/src/test/java/net/openhft/chronicle/map/jsr166/map/LoopHelpers.java index d30aa2fcc..4a843d7d2 100644 --- a/src/test/java/net/openhft/chronicle/map/jsr166/map/LoopHelpers.java +++ b/src/test/java/net/openhft/chronicle/map/jsr166/map/LoopHelpers.java @@ -157,7 +157,7 @@ public MarsagliaRandom() { } public int next() { - int t = x ^ (x << 11); + final int t = x ^ (x << 11); x = y; y = z; z = w; @@ -204,8 +204,9 @@ public void run() { if (!started) { started = true; startTime = t; - } else + } else { endTime = t; + } } public void clear() { diff --git a/src/test/java/net/openhft/chronicle/map/jsr166/map/MapCheck.java b/src/test/java/net/openhft/chronicle/map/jsr166/map/MapCheck.java index 0a5891814..1020822ee 100644 --- a/src/test/java/net/openhft/chronicle/map/jsr166/map/MapCheck.java +++ b/src/test/java/net/openhft/chronicle/map/jsr166/map/MapCheck.java @@ -29,7 +29,7 @@ public class MapCheck { static final String MISSING = "MISSING"; static final LoopHelpers.SimpleRandom srng = new LoopHelpers.SimpleRandom(); static final Random rng = new Random(3152688); - static TestTimer timer = new TestTimer(); + static final TestTimer timer = new TestTimer(); static Class eclass; static volatile int checkSum; static int counter = 0; @@ -39,11 +39,9 @@ static void reallyAssert(boolean b) { } public static void main(String[] args) throws IOException, ClassNotFoundException { - int numTests = 20; - int size = 36864; // about midway of HashMap resize interval - - if (args.length == 0) + if (args.length == 0) { System.out.println("Usage: MapCheck mapclass [int|float|string|object] [trials] [size] [serialtest]"); + } if (args.length > 1) { String et = args[1].toLowerCase(); @@ -56,18 +54,31 @@ else if (et.startsWith("s")) else if (et.startsWith("d")) eclass = java.lang.Double.class; } - if (eclass == null) + if (eclass == null) { eclass = Integer.class; + } - if (args.length > 2) + int numTests = 20; + int size = 36864; // about midway of HashMap resize interval + + if (args.length > 2) { numTests = Integer.parseInt(args[2]); + } - if (args.length > 3) + if (args.length > 3) { size = Integer.parseInt(args[3]); + } boolean doSerializeTest = args.length > 4; - while ((size & 3) != 0) ++size; + runTests(numTests, size, doSerializeTest); + } + + private static void runTests(int numTests, int size, boolean doSerializeTest) + throws IOException, ClassNotFoundException { + while ((size & 3) != 0) { + ++size; + } System.out.print(" elements: " + eclass.getName()); System.out.print(" trials: " + numTests); @@ -92,8 +103,9 @@ else if (et.startsWith("d")) checkNullKey(); - if (doSerializeTest) + if (doSerializeTest) { serTest(size); + } } static Map newMap() { @@ -147,10 +159,7 @@ static void checkNullKey() { try { m.put(null, x); v = m.get(null); - } catch (NullPointerException npe) { - System.out.println("Map does not allow null keys"); - return; - } catch (IllegalArgumentException npe) { + } catch (NullPointerException | IllegalArgumentException npe) { System.out.println("Map does not allow null keys"); return; } @@ -392,7 +401,7 @@ static void mainTest(Object[] key, Object[] absent) { reallyAssert(s.size() == size); untimedKeyTest("Access Present ", size, s, key, size); keyTest("Search Absent ", size, s, absent, 0); -// No supported: valTest(s, key); + // No supported: valTest(s, key); remTest("Search Absent ", size, s, absent, 0); reallyAssert(s.size() == size); remHalfTest("Remove Present ", size, s, key, size / 2); @@ -442,10 +451,10 @@ static void twoMapTest2(Map s, Object[] key, Object[] absent) { Object lastkey = kitTest(s2, size); Object hold = s2.get(lastkey); - int sum = 0; timer.start("Traverse entry ", size * 12); // 12 until finish + int sum = 0; int sh1 = s.hashCode() - s2.hashCode(); reallyAssert(sh1 == 0); boolean eq1 = s2.equals(s); @@ -542,19 +551,20 @@ static void initializeKeys(Object[] key, Object[] absent, int size) { initDoubles(key, absent, size); } else if (eclass == String.class) { initWords(size, key, absent); - } else + } else { throw new Error("unknown type"); + } } static void initInts(Object[] key, Object[] absent, int size) { for (int i = 0; i < size; ++i) - key[i] = Integer.valueOf(i); + key[i] = i; Map m = newMap(); int k = 0; while (k < size) { int r = srng.next(); if (r < 0 || r >= size) { - Integer ir = Integer.valueOf(r); + Integer ir = r; if (m.put(ir, ir) == null) absent[k++] = ir; } @@ -581,9 +591,8 @@ static void initFloats(Object[] key, Object[] absent, int size) { static void initDoubles(Object[] key, Object[] absent, int size) { Map m = newMap(); for (int i = 0; i < size; ++i) { - double r = (double) i; - key[i] = r; - m.put(r, r); + key[i] = (double) i; + m.put((double) i, (double) i); } int k = 0; while (k < size) { @@ -689,8 +698,9 @@ static void printStats() { if (n == 0) { n = stats.firstn; s = stats.first; - } else + } else { s = stats.sum; + } double t = ((double) s) / n; long nano = Math.round(t); @@ -718,8 +728,8 @@ void finish() { static final class Stats { long sum; long number; - long first; - long firstn; + final long first; + final long firstn; Stats(long t, long n) { first = t; diff --git a/src/test/java/net/openhft/chronicle/map/locks/DirtyReadIntolerant.java b/src/test/java/net/openhft/chronicle/map/locks/DirtyReadIntolerant.java index dd16358f4..b052fcb00 100644 --- a/src/test/java/net/openhft/chronicle/map/locks/DirtyReadIntolerant.java +++ b/src/test/java/net/openhft/chronicle/map/locks/DirtyReadIntolerant.java @@ -23,10 +23,9 @@ public static void main(String[] args) { args[3] + "OPERAND_CHRONICLE_MAP" ); - Double coupon = 0.00; + double coupon = 0.00; BondVOInterface bond = newNativeReference(BondVOInterface.class); //BondVOInterface cslMock = newNativeReference(BondVOInterface.class); //mock'd - long stamp = 0; System.out.println( " ,,@t=" + System.currentTimeMillis() + " DirtyReadIntolerant ENTERING offHeapLock.readLock()" @@ -41,7 +40,9 @@ public static void main(String[] args) { " DirtyReadIntolerant sleeping " + sleepMock + " seconds" ); Thread.sleep(sleepMock * 1_000); + long stamp = 0; while ((stamp = offHeapLock.readLock()) < 0) { + Thread.yield(); } System.out.println( " ,,@t=" + System.currentTimeMillis() + diff --git a/src/test/java/net/openhft/chronicle/map/locks/DirtyReadIntolerant_ReaderReader_Test.java b/src/test/java/net/openhft/chronicle/map/locks/DirtyReadIntolerant_ReaderReader_Test.java index ccea7e504..ea5f7ab56 100644 --- a/src/test/java/net/openhft/chronicle/map/locks/DirtyReadIntolerant_ReaderReader_Test.java +++ b/src/test/java/net/openhft/chronicle/map/locks/DirtyReadIntolerant_ReaderReader_Test.java @@ -37,10 +37,9 @@ public void main() { DirtyReadTolerance.offHeap( OS.getTarget() + "/shm-OPERAND_CHRONICLE_MAP" ); - Double coupon = 0.00; + double coupon = 0.00; BondVOInterface bond = newNativeReference(BondVOInterface.class); //BondVOInterface cslMock = newNativeReference(BondVOInterface.class); //mock'd - long stamp = 0; System.out.println( " " + " ,,@t=" + System.currentTimeMillis() + @@ -57,6 +56,7 @@ public void main() { " DirtyReadIntolerant sleeping " + sleepMock + " seconds" ); Thread.sleep(sleepMock * 1_000); + long stamp = 0; while ((stamp = offHeapLock.tryReadLock()) < 0) { Assert.assertEquals(Boolean.TRUE, false); // we failed! } diff --git a/src/test/java/net/openhft/chronicle/map/locks/DirtyReadOffender.java b/src/test/java/net/openhft/chronicle/map/locks/DirtyReadOffender.java index d9aa30003..74aa0a8b9 100644 --- a/src/test/java/net/openhft/chronicle/map/locks/DirtyReadOffender.java +++ b/src/test/java/net/openhft/chronicle/map/locks/DirtyReadOffender.java @@ -31,7 +31,7 @@ public static void main(String[] args) { " @t=" + System.currentTimeMillis() + " DirtyReadOffender established chm " ); - StampedLock offHeapLock = new ChronicleStampedLock( + final StampedLock offHeapLock = new ChronicleStampedLock( args[3] + "OPERAND_ChronicleStampedLock" ); @@ -61,6 +61,7 @@ public static void main(String[] args) { " DirtyReadOffender ACQUIRING offHeapLock.writeLock();" ); while ((stamp = offHeapLock.writeLock()) == 0) { + Thread.yield(); } System.out.println( " @t=" + System.currentTimeMillis() + diff --git a/src/test/java/net/openhft/chronicle/map/locks/DirtyReadOffenderIPCTest.java b/src/test/java/net/openhft/chronicle/map/locks/DirtyReadOffenderIPCTest.java index 796319a5f..3b8c9c193 100644 --- a/src/test/java/net/openhft/chronicle/map/locks/DirtyReadOffenderIPCTest.java +++ b/src/test/java/net/openhft/chronicle/map/locks/DirtyReadOffenderIPCTest.java @@ -5,7 +5,6 @@ import net.openhft.chronicle.core.OS; import net.openhft.chronicle.map.ChronicleMap; -import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -36,7 +35,7 @@ public void run() { "..... @t=" + System.currentTimeMillis() + " DirtyReadOffender established chm " ); - StampedLock offHeapLock = new ChronicleStampedLock( + final StampedLock offHeapLock = new ChronicleStampedLock( OS.getTarget() + "/shm-" + "OPERAND_ChronicleStampedLock" ); @@ -65,7 +64,7 @@ public void run() { " DirtyReadOffender ACQUIRING offHeapLock.writeLock();" ); while ((stamp = offHeapLock.writeLock()) == 0) { - ; // none + // none } System.out.println( "..... @t=" + System.currentTimeMillis() + diff --git a/src/test/java/net/openhft/chronicle/map/locks/DirtyReadOffenderTest.java b/src/test/java/net/openhft/chronicle/map/locks/DirtyReadOffenderTest.java index 908174d75..c65851075 100644 --- a/src/test/java/net/openhft/chronicle/map/locks/DirtyReadOffenderTest.java +++ b/src/test/java/net/openhft/chronicle/map/locks/DirtyReadOffenderTest.java @@ -34,7 +34,7 @@ public void run() { "..... @t=" + System.currentTimeMillis() + " DirtyReadOffender established chm " ); - StampedLock offHeapLock = new ChronicleStampedLock( + final StampedLock offHeapLock = new ChronicleStampedLock( OS.getTarget() + "/shm-" + "OPERAND_ChronicleStampedLock" ); @@ -63,7 +63,7 @@ public void run() { " DirtyReadOffender ACQUIRING offHeapLock.writeLock();" ); while ((stamp = offHeapLock.writeLock()) == 0) { - ; // none + // none } System.out.println( "..... @t=" + System.currentTimeMillis() + diff --git a/src/test/java/net/openhft/chronicle/map/locks/DirtyReadOffender_ReaderWriterTest.java b/src/test/java/net/openhft/chronicle/map/locks/DirtyReadOffender_ReaderWriterTest.java index 6871d3346..f989f4cd5 100644 --- a/src/test/java/net/openhft/chronicle/map/locks/DirtyReadOffender_ReaderWriterTest.java +++ b/src/test/java/net/openhft/chronicle/map/locks/DirtyReadOffender_ReaderWriterTest.java @@ -22,7 +22,7 @@ public void longRunningStableOnLinux() { @Test(timeout = 60_000) public void main() { try { - long sleepT = Long.parseLong("8"); + final long sleepT = Long.parseLong("8"); long holdTime = Long.parseLong("20"); Thread tooThread = new Thread(new ReaderToo()); @@ -42,7 +42,7 @@ public void main() { OS.getTarget() + "/shm-" + "OPERAND_ChronicleStampedLock" ); - Assert.assertNotEquals(offHeapLock, null); + Assert.assertNotEquals(null, offHeapLock); BondVOInterface bond = newNativeReference(BondVOInterface.class); //BondVOInterface cslMock = newNativeReference(BondVOInterface.class); chm.acquireUsing("369604101", bond); @@ -82,7 +82,7 @@ public void main() { ); } - Assert.assertNotEquals(blockedByHoldingReaderCount, 0); + Assert.assertNotEquals(0, blockedByHoldingReaderCount); System.out.println( " " + " @t=" + System.currentTimeMillis() + diff --git a/src/test/java/net/openhft/chronicle/map/locks/DirtyReadOffender_WriterReaderTest.java b/src/test/java/net/openhft/chronicle/map/locks/DirtyReadOffender_WriterReaderTest.java index 442596161..4409f0c10 100644 --- a/src/test/java/net/openhft/chronicle/map/locks/DirtyReadOffender_WriterReaderTest.java +++ b/src/test/java/net/openhft/chronicle/map/locks/DirtyReadOffender_WriterReaderTest.java @@ -5,7 +5,6 @@ import net.openhft.chronicle.core.OS; import net.openhft.chronicle.map.ChronicleMap; -import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -23,7 +22,7 @@ public void longRunningStableOnLinux() { @Test public void main() { try { - long sleepT = Long.parseLong("8"); + final long sleepT = Long.parseLong("8"); long holdTime = Long.parseLong("20"); Thread tooThread = new Thread(new WriterToo()); @@ -43,7 +42,7 @@ public void main() { OS.getTarget() + "/shm-" + "OPERAND_ChronicleStampedLock" ); - Assert.assertNotEquals(offHeapLock, null); + Assert.assertNotEquals(null, offHeapLock); BondVOInterface bond = newNativeReference(BondVOInterface.class); //BondVOInterface cslMock = newNativeReference(BondVOInterface.class); chm.acquireUsing("369604101", bond); @@ -83,7 +82,7 @@ public void main() { ); } - Assert.assertNotEquals(blockedByHoldingWriterCount, 0); + Assert.assertNotEquals(0, blockedByHoldingWriterCount); System.out.println( " " + " @t=" + System.currentTimeMillis() + diff --git a/src/test/java/net/openhft/chronicle/map/locks/DirtyReadOffender_WriterWriterTest.java b/src/test/java/net/openhft/chronicle/map/locks/DirtyReadOffender_WriterWriterTest.java index b2e3a9a48..72d4aba0a 100644 --- a/src/test/java/net/openhft/chronicle/map/locks/DirtyReadOffender_WriterWriterTest.java +++ b/src/test/java/net/openhft/chronicle/map/locks/DirtyReadOffender_WriterWriterTest.java @@ -5,7 +5,6 @@ import net.openhft.chronicle.core.OS; import net.openhft.chronicle.map.ChronicleMap; -import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -23,7 +22,7 @@ public void longRunningStableOnLinux() { @Test public void main() { try { - long sleepT = Long.parseLong("8"); + final long sleepT = Long.parseLong("8"); long holdTime = Long.parseLong("20"); Thread tooThread = new Thread(new WriterToo()); @@ -43,7 +42,7 @@ public void main() { OS.getTarget() + "/shm-" + "OPERAND_ChronicleStampedLock" ); - Assert.assertNotEquals(offHeapLock, null); + Assert.assertNotEquals(null, offHeapLock); BondVOInterface bond = newNativeReference(BondVOInterface.class); //BondVOInterface cslMock = newNativeReference(BondVOInterface.class); chm.acquireUsing("369604101", bond); @@ -83,7 +82,7 @@ public void main() { ); } - Assert.assertNotEquals(blockedByHoldingWriterCount, 0); + Assert.assertNotEquals(0, blockedByHoldingWriterCount); System.out.println( " " + " @t=" + System.currentTimeMillis() + diff --git a/src/test/java/net/openhft/chronicle/map/locks/DirtyReadVictim.java b/src/test/java/net/openhft/chronicle/map/locks/DirtyReadVictim.java index 91b9c3223..840ecae10 100644 --- a/src/test/java/net/openhft/chronicle/map/locks/DirtyReadVictim.java +++ b/src/test/java/net/openhft/chronicle/map/locks/DirtyReadVictim.java @@ -24,10 +24,9 @@ public static void main(String[] args) { args[3] + "OPERAND_CHRONICLE_MAP" ); - Double coupon = 0.00; + double coupon = 0.00; BondVOInterface bond = newNativeReference(BondVOInterface.class); //BondVOInterface cslMock = newNativeReference(BondVOInterface.class); //mock'd - long stamp = 0; System.out.println( " ,,@t=" + System.currentTimeMillis() + " DirtyReadVictim ENTERING offHeapLock.tryOptimisticRead()" @@ -43,6 +42,7 @@ public static void main(String[] args) { ); Thread.sleep(sleepMock * 1_000); + long stamp = 0; while ((stamp = offHeapLock.tryOptimisticRead()) < 0) { System.out.println( " ,,@t=" + System.currentTimeMillis() + diff --git a/src/test/java/net/openhft/chronicle/map/locks/DirtyReadVictimIPCTest.java b/src/test/java/net/openhft/chronicle/map/locks/DirtyReadVictimIPCTest.java index f54930966..674af470c 100644 --- a/src/test/java/net/openhft/chronicle/map/locks/DirtyReadVictimIPCTest.java +++ b/src/test/java/net/openhft/chronicle/map/locks/DirtyReadVictimIPCTest.java @@ -5,13 +5,10 @@ import net.openhft.chronicle.core.OS; import net.openhft.chronicle.map.ChronicleMap; -import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; -import java.io.IOException; - import static net.openhft.chronicle.values.Values.newNativeReference; import static org.junit.Assume.assumeFalse; @@ -35,36 +32,36 @@ public void longRunningStableOnLinux() { */ @Test - public void mainOptimisticNegative() throws IOException { + public void mainOptimisticNegative() { try { System.out.println("\n***** Optimistic (-) Test\n"); -// ProcessBuilder pb = new ProcessBuilder( -// "/usr/bin/mkdir -p "+ -// " C:\\Users\\buddy\\dev\\shm\\ " -// ); - -// Process p = pb.start(); -// Scanner scan = new Scanner(p.getInputStream()); -// while (scan.hasNext()) { -// System.out.println( -// " ,,@t=" + -// System.currentTimeMillis() + -// " DirtyReadVictimTest CALLING [" + -// scan.next() + -// "]" -// ); -// } -// Thread.sleep(1_000); -// p.destroyForcibly(); -// System.out.println( -// " ,,@t=" + -// System.currentTimeMillis() + -// " DirtyReadVictimTest called [\n" + -// "mkdir -p " + -// " C:\\Users\\buddy\\dev\\shm\\ " + -// "\n" + -// "]" -// ); + // ProcessBuilder pb = new ProcessBuilder( + // "/usr/bin/mkdir -p "+ + // " C:\\Users\\buddy\\dev\\shm\\ " + // ); + // + // Process p = pb.start(); + // Scanner scan = new Scanner(p.getInputStream()); + // while (scan.hasNext()) { + // System.out.println( + // " ,,@t=" + + // System.currentTimeMillis() + + // " DirtyReadVictimTest CALLING [" + + // scan.next() + + // "]" + // ); + // } + // Thread.sleep(1_000); + // p.destroyForcibly(); + // System.out.println( + // " ,,@t=" + + // System.currentTimeMillis() + + // " DirtyReadVictimTest called [\n" + + // "mkdir -p " + + // " C:\\Users\\buddy\\dev\\shm\\ " + + // "\n" + + // "]" + // ); /* ben.cotton@rutgers.edu START @@ -74,7 +71,7 @@ public void mainOptimisticNegative() throws IOException { DirtyReadTolerance.offHeap( OS.getTarget() + "/shm-OPERAND_CHRONICLE_MAP" ); - Double coupon = 0.00; + double coupon = 0.00; BondVOInterface bond = newNativeReference(BondVOInterface.class); long stamp; System.out.println( @@ -86,7 +83,7 @@ public void mainOptimisticNegative() throws IOException { "OPERAND_ChronicleStampedLock" ); while ((stamp = offHeapLock.tryOptimisticRead()) == 0) { - ; // none + // none } System.out.println( " ,,@t=" + System.currentTimeMillis() + @@ -115,8 +112,8 @@ public void mainOptimisticNegative() throws IOException { Thread.sleep(20_000); } finally { - boolean r; - if ((r = offHeapLock.validate(stamp))) { + boolean r = offHeapLock.validate(stamp); + if (r) { System.out.println( " ,,@t=" + System.currentTimeMillis() + " DirtyReadVictim OPTIMISTICALLY_READ coupon=" + @@ -169,7 +166,7 @@ public void mainOptimisticPositive() { DirtyReadTolerance.offHeap( OS.getTarget() + "/shm-OPERAND_CHRONICLE_MAP" ); - Double coupon = 0.00; + double coupon = 0.00; BondVOInterface bond = newNativeReference(BondVOInterface.class); long stamp = 0; System.out.println( @@ -181,7 +178,7 @@ public void mainOptimisticPositive() { + "OPERAND_ChronicleStampedLock" ); while ((stamp = offHeapLock.tryOptimisticRead()) == 0) { - ; // none + // none } System.out.println( " ,,@t=" + System.currentTimeMillis() + diff --git a/src/test/java/net/openhft/chronicle/map/locks/DirtyReadVictimTest.java b/src/test/java/net/openhft/chronicle/map/locks/DirtyReadVictimTest.java index 18bd21dd7..2ad3c93c7 100644 --- a/src/test/java/net/openhft/chronicle/map/locks/DirtyReadVictimTest.java +++ b/src/test/java/net/openhft/chronicle/map/locks/DirtyReadVictimTest.java @@ -5,13 +5,10 @@ import net.openhft.chronicle.core.OS; import net.openhft.chronicle.map.ChronicleMap; -import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; -import java.io.IOException; - import static net.openhft.chronicle.values.Values.newNativeReference; import static org.junit.Assume.assumeFalse; @@ -24,7 +21,7 @@ public void longRunningStableOnLinux() { } @Test - public void mainOptimisticNegative() throws IOException { + public void mainOptimisticNegative() { try { System.out.println("\n***** Optimistic (-) Test\n"); @@ -36,7 +33,7 @@ public void mainOptimisticNegative() throws IOException { DirtyReadTolerance.offHeap( OS.getTarget() + "/shm-OPERAND_CHRONICLE_MAP" ); - Double coupon = 0.00; + double coupon = 0.00; BondVOInterface bond = newNativeReference(BondVOInterface.class); long stamp; System.out.println( @@ -48,6 +45,7 @@ public void mainOptimisticNegative() throws IOException { "OPERAND_ChronicleStampedLock" ); while ((stamp = offHeapLock.tryOptimisticRead()) == 0) { + Thread.yield(); } System.out.println( " ,,@t=" + System.currentTimeMillis() + @@ -76,8 +74,8 @@ public void mainOptimisticNegative() throws IOException { Thread.sleep(20_000); } finally { - boolean r; - if ((r = offHeapLock.validate(stamp))) { + boolean r = offHeapLock.validate(stamp); + if (r) { System.out.println( " ,,@t=" + System.currentTimeMillis() + " DirtyReadVictim OPTIMISTICALLY_READ coupon=" + @@ -132,7 +130,7 @@ public void mainOptimisticPositive() { DirtyReadTolerance.offHeap( OS.getTarget() + "/shm-OPERAND_CHRONICLE_MAP" ); - Double coupon = 0.00; + double coupon = 0.00; BondVOInterface bond = newNativeReference(BondVOInterface.class); long stamp = 0; System.out.println( @@ -144,6 +142,7 @@ public void mainOptimisticPositive() { + "OPERAND_ChronicleStampedLock" ); while ((stamp = offHeapLock.tryOptimisticRead()) == 0) { + Thread.yield(); } System.out.println( " ,,@t=" + System.currentTimeMillis() + diff --git a/src/test/java/net/openhft/chronicle/map/locks/ReaderToo.java b/src/test/java/net/openhft/chronicle/map/locks/ReaderToo.java index beb2f6fb2..9926e604c 100644 --- a/src/test/java/net/openhft/chronicle/map/locks/ReaderToo.java +++ b/src/test/java/net/openhft/chronicle/map/locks/ReaderToo.java @@ -23,10 +23,9 @@ public void run() { DirtyReadTolerance.offHeap( OS.getTarget() + "/shm-OPERAND_CHRONICLE_MAP" ); - Double coupon = 0.00; + double coupon = 0.00; BondVOInterface bond = newNativeReference(BondVOInterface.class); //BondVOInterface cslMock = newNativeReference(BondVOInterface.class); //mock'd - long stamp = 0; System.out.println( "READER_TOO " + " ,,@t=" + System.currentTimeMillis() + @@ -43,8 +42,9 @@ public void run() { " DirtyReadIntolerant sleeping " + sleepMock + " seconds" ); Thread.sleep(sleepMock * 1_000); + long stamp = 0; while ((stamp = offHeapLock.tryReadLock()) < 0) { - //Assert.assertEquals(Boolean.TRUE, false); // we failed!; + Thread.yield(); } //Assert.assertEquals(Boolean.TRUE, true); // we passed System.out.println( diff --git a/src/test/java/net/openhft/chronicle/map/locks/WriterToo.java b/src/test/java/net/openhft/chronicle/map/locks/WriterToo.java index aa5e95d33..74761d6c9 100644 --- a/src/test/java/net/openhft/chronicle/map/locks/WriterToo.java +++ b/src/test/java/net/openhft/chronicle/map/locks/WriterToo.java @@ -14,7 +14,7 @@ class WriterToo implements Runnable { @Override public void run() { try { - long sleepT = 0; + final long sleepT = 0; long holdTime = 20; ChronicleMap chm = @@ -31,7 +31,7 @@ public void run() { OS.getTarget() + "/shm-" + "OPERAND_ChronicleStampedLock" ); - Assert.assertNotEquals(offHeapLock, null); + Assert.assertNotEquals(null, offHeapLock); BondVOInterface bond = newNativeReference(BondVOInterface.class); //BondVOInterface cslMock = newNativeReference(BondVOInterface.class); chm.acquireUsing("369604101", bond); @@ -61,6 +61,7 @@ public void run() { " DirtyReadOffender ACQUIRING offHeapLock.writeLock();" ); while ((stamp = offHeapLock.writeLock()) == 0) { + Thread.yield(); } System.out.println( "WRITER TOO" + diff --git a/src/test/java/net/openhft/chronicle/map/utility/ProcessInstanceLimiter.java b/src/test/java/net/openhft/chronicle/map/utility/ProcessInstanceLimiter.java index 505121784..492e2e41c 100644 --- a/src/test/java/net/openhft/chronicle/map/utility/ProcessInstanceLimiter.java +++ b/src/test/java/net/openhft/chronicle/map/utility/ProcessInstanceLimiter.java @@ -20,6 +20,7 @@ import java.io.File; import java.io.IOException; +import java.nio.file.FileSystems; import java.util.Date; import java.util.Map; import java.util.Map.Entry; @@ -116,7 +117,7 @@ public ProcessInstanceLimiter() throws IOException { * @throws IOException - if the default shared file cannot be created */ public ProcessInstanceLimiter(Callback callback) throws IOException { - this(DEFAULT_SHARED_MAP_DIRECTORY + System.getProperty("file.separator") + DEFAULT_SHARED_MAP_NAME, callback); + this(DEFAULT_SHARED_MAP_DIRECTORY + FileSystems.getDefault().getSeparator() + DEFAULT_SHARED_MAP_NAME, callback); } /** @@ -142,7 +143,7 @@ public ProcessInstanceLimiter(String sharedMapPath, Callback callback) throws IO t.start(); } - public static void main(String[] args) throws IOException, InterruptedException { + public static void main(String[] args) throws IOException { ProcessInstanceLimiter.limitTo(2); Jvm.pause(60L * 1000L); } @@ -280,7 +281,7 @@ public void run() { Set> entrySet = this.localUpdates.entrySet(); for (Entry entry : entrySet) { processType = entry.getKey(); - int index = entry.getValue().intValue(); + int index = entry.getValue(); Data data = this.timedata.get(processType); if (data == null) { entrySet.remove(entry); @@ -387,13 +388,9 @@ public void setMaxNumberOfProcessesOfType(String processType, int maxNumberOfPro if (data.getMaxNumberOfProcessesAllowed() != maxNumberOfProcessesAllowed) { //it's either a new object, set to 0, or //another process set it to an invalid value - if (data.compareAndSwapMaxNumberOfProcessesAllowed(0, maxNumberOfProcessesAllowed)) { - //What we expected, everything's good - } else { - //something else set a value, if it's not 2 we've got a conflict - if (data.getMaxNumberOfProcessesAllowed() != maxNumberOfProcessesAllowed) { - throw new IllegalArgumentException("The existing shared map already specifies that the maximum number of processes allowed is " + data.getMaxNumberOfProcessesAllowed() + " and changing that to " + maxNumberOfProcessesAllowed + " is not supported"); - } + if (!data.compareAndSwapMaxNumberOfProcessesAllowed(0, maxNumberOfProcessesAllowed) + && data.getMaxNumberOfProcessesAllowed() != maxNumberOfProcessesAllowed) { + throw new IllegalArgumentException("The existing shared map already specifies that the maximum number of processes allowed is " + data.getMaxNumberOfProcessesAllowed() + " and changing that to " + maxNumberOfProcessesAllowed + " is not supported"); } } String name = processType + '#'; diff --git a/src/test/java/net/openhft/chronicle/set/Builder.java b/src/test/java/net/openhft/chronicle/set/Builder.java index aeb1188e9..a8aa8943e 100644 --- a/src/test/java/net/openhft/chronicle/set/Builder.java +++ b/src/test/java/net/openhft/chronicle/set/Builder.java @@ -19,7 +19,7 @@ public class Builder { public static final int SIZE = 10_000; // added to ensure uniqueness static int count; - static String WIN_OS = "WINDOWS"; + static final String WIN_OS = "WINDOWS"; public static File getPersistenceFile() throws IOException { @@ -29,8 +29,7 @@ public static File getPersistenceFile() throws IOException { if (System.getProperty("os.name").indexOf(WIN_OS) > 0) { /*Windows will lock a file that are currently in use. You cannot delete it, however, using setwritable() and then releasing RandomRW lock adds the file to JVM exit cleanup. - This will only work if the user is an admin on windows. - */ + This will only work if the user is an admin on windows. */ file.setWritable(true);//just in case relative path was used. try (RandomAccessFile raf = new RandomAccessFile(file, "rw")) { //allows closing the file access on windows. forcing to close access. Only works for admin-access. diff --git a/src/test/java/net/openhft/chronicle/set/Issue24ChronicleSetTest.java b/src/test/java/net/openhft/chronicle/set/Issue24ChronicleSetTest.java index 870ae6a19..a4098888a 100644 --- a/src/test/java/net/openhft/chronicle/set/Issue24ChronicleSetTest.java +++ b/src/test/java/net/openhft/chronicle/set/Issue24ChronicleSetTest.java @@ -26,15 +26,14 @@ H init(B builder, int entrySize, int averageKeySize) throws IOException { File file = File.createTempFile("stringSet", ".dat"); file.deleteOnExit(); try { - H result = builder.entries(entrySize) + return builder.entries(entrySize) .averageKeySize(averageKeySize).createPersistedTo(file); - return result; } catch (IOException ioe) { throw new RuntimeException(ioe); } } - public synchronized static ChronicleSet initSet( + public static synchronized ChronicleSet initSet( Class entryClass, int entrySize, int averageKeySize) throws IOException { return init(ChronicleSetBuilder.of(entryClass), entrySize, averageKeySize); @@ -51,7 +50,7 @@ public void issue24ChronicleSetTest() throws IOException { } executor.shutdown(); while (!executor.isTerminated()) { - + Thread.yield(); } System.out.println("Finished all threads"); diff --git a/src/test/java/net/openhft/chronicle/set/Issue3Test.java b/src/test/java/net/openhft/chronicle/set/Issue3Test.java index 29df0c3bf..59740d9dc 100644 --- a/src/test/java/net/openhft/chronicle/set/Issue3Test.java +++ b/src/test/java/net/openhft/chronicle/set/Issue3Test.java @@ -6,14 +6,13 @@ import org.junit.Ignore; import org.junit.Test; -import java.io.IOException; import java.util.Random; public class Issue3Test { @Ignore("https://teamcity.chronicle.software/viewLog.html?buildId=639348&tab=buildResultsDiv&buildTypeId=OpenHFT_BuildAll_BuildJava8compileJava8") @Test - public void test() throws IOException { + public void test() { try (ChronicleSet set = ChronicleSetBuilder.of(Long.class) .actualSegments(1) .entriesPerSegment(1000) diff --git a/src/test/java/net/openhft/lang/values/DoubleArray.java b/src/test/java/net/openhft/lang/values/DoubleArray.java index 0919d0243..525583e8f 100644 --- a/src/test/java/net/openhft/lang/values/DoubleArray.java +++ b/src/test/java/net/openhft/lang/values/DoubleArray.java @@ -8,7 +8,6 @@ import net.openhft.chronicle.bytes.DynamicallySized; import net.openhft.chronicle.values.Copyable; -import java.io.IOException; import java.nio.channels.FileLock; /** @@ -54,12 +53,12 @@ public long maxSize() { } @Override - public FileLock lock(boolean shared) throws IOException { + public FileLock lock(boolean shared) { throw new UnsupportedOperationException(); } @Override - public FileLock tryLock(boolean shared) throws IOException { + public FileLock tryLock(boolean shared) { throw new UnsupportedOperationException(); }