【问题标题】:Guava multimap using Random Access file?使用随机访问文件的番石榴多图?
【发布时间】:2012-10-01 07:14:27
【问题描述】:

我有一个 Integer[]s 文件太大而无法放入内存。我想搜索所有最后一个成员 x 的数组并在其他代码中使用它们。有没有办法使用 Guava 的多重映射来做到这一点,其中 x 是键并存储在内存中,而 Integer[] 是值并存储在磁盘上?在这种情况下,键不是唯一的,但键值对是唯一的。读取这个多图(假设它是可能的)将是并发的。我也愿意接受其他方法的建议来解决这个问题。
谢谢

【问题讨论】:

    标签: java io guava bigdata


    【解决方案1】:

    您可以创建一个表示磁盘上的数组的类(基于它在数组文件中的索引),我们称之为FileBackedIntArray,并将其实例作为HashMultimap<Integer, FileBackedIntArray> 的值:

    public class FileBackedIntArray {
        // Index of the array in the file of arrays
        private final int index;
        private final int lastElement;
    
        public FileBackedIntArray(int index, int lastElement) {
            this.index = index;
            this.lastElement = lastElement;
        }
    
        public int getIndex() {
            return index;
        }
    
        public int[] readArray() {
            // Read the file and deserialize the array at the associated index
            return smth;
        }
    
        public int getLastElement() {
            return lastElement;
        }
    
        @Override
        public int hashCode() {
            return index;
        }
    
        @Override
        public boolean equals(Object o) {
            if (this == o) {
                return true;
            } else if (o == null || o.getClass() != getClass()) {
                return false;
            }
    
            return index == ((FileBackedIntArray) o).index;
        }
    }
    

    顺便说一句,你真的需要Integer[] 而不是int[](即你可以有null 值)吗? 正如你在 cmets 中所说,你不需要' 真的不需要Integer[],因此在任何地方使用intss 将避免装箱/拆箱,并且会节省大量空间,因为您似乎有很多空间。希望最后一个元素 (x) 没有大量可能的值。

    然后您为每个数组创建一个实例并读取最后一个元素以将其放入Multimap,而无需保留数组。填充Multimap 需要是顺序的,或者如果并发,则需要使用锁进行保护,但读取可以是并发的,没有任何保护。您甚至可以在填充 HashMultimap 后创建一个 ImmutableMultimap,以防止任何修改,这是并发环境中的安全做法。

    【讨论】:

    • 我检查了程序,不,我不需要 Integer[],int[] 可以工作。
    • @blue 好的,我编辑了答案以考虑到这一点。但这有用吗?
    猜你喜欢
    • 1970-01-01
    • 2012-04-13
    • 1970-01-01
    • 1970-01-01
    • 2012-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多