简体   繁体   English

java中BlockingQueue / ArrayBlockingQueue的序列化

[英]Serialization of BlockingQueue/ArrayBlockingQueue in java

I need to "serialize" a large BlockingQueue(sizeof 10_000) that contains domanis names (Strings(Objects) ) for my crawler - for example if I will stop stop it or it will happen accidentally - this will help not to crawl that was already done. 我需要为我的抓取工具“序列化”包含domanis名称(字符串(对象))的大型BlockingQueue(sizeof 10_000) - 例如,如果我将停止它或意外发生 - 这将有助于不抓取已经完成。 What is the best way to do it? 最好的方法是什么? In NET I have used the binary serialization for such tasks (like protobuf for example) (it is faster and serialized information visualization not so critical for understanding -so not necessary XML view). 在.NET中,我使用了二进制序列化来完成这样的任务(例如protobuf)(它更快,序列化的信息可视化对于理解不那么重要 - 所以不是必要的XML视图)。 But how to do this in java? 但是如何在java中做到这一点? May be you an reference on a sample? 您可以参考样品吗?

BlockingQueue is just an interface, not a concrete type. BlockingQueue只是一个接口,而不是具体的类型。 You serialize/deserialize instances which have concrete types. 您序列化/反序列化具有具体类型的实例 It depends whether the dynamic type of the instace you have implements Serializable . 这取决于您实现的实例的动态类型是否可实现Serializable

ArrayBlockingQueue implements Serializable which means you can simply serialize it and deserialize it with an ObjectInputStream / ObjectOutputStream : ArrayBlockingQueue实现Serializable ,这意味着您可以简单地序列化它并使用ObjectInputStream / ObjectOutputStream对其进行反序列化:

Saving an ArrayBlockingQueue : 保存ArrayBlockingQueue

ArrayBlockingQueue queue = new ArrayBlockingQueue(10);

try (ObjectOutputStream out = new ObjectOutputStream(
        new FileOutputStream("queue.data"))) {
    out.writeObject(queue);
}

Reading a persisted ArrayBlockingQueue : 读取持久化的ArrayBlockingQueue

ArrayBlockingQueue queue = null;

try (ObjectInputStream in = new ObjectInputStream (
        new FileInputStream("queue.data"))) {
    queue = in.readObject()
}

BlockingQueue interface in java has implementation by some classes such as ArrayBlockingQueue, DelayQueue, LinkedBlockingQueue, and others. java中的BlockingQueue接口由一些类实现,例如ArrayBlockingQueue,DelayQueue,LinkedBlockingQueue等。

Below are important methods of blocking queues. 以下是阻止队列的重要方法。

E take() - consumes element from queue, waits if queue is empty until producer produces something into the queue. E take() - 消耗队列中的元素,等待队列为空,直到生产者将某些东西放入队列。

put(E) - producer puts element into queue, waits if queue is full until consumer consumes item(s) from the queue. put(E) - producer将元素放入队列,等待队列满,直到消费者从队列中消耗项目。

more info @ oracle docs . 更多信息@ oracle docs

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM