Java: Keep order using threads

时间:2015-07-28 16:52:32

标签: java multithreading collections

I have multiple threads that log some info throug my svc object.

public class SomeObject implements Runnable {
    @Override
    public void run() {
        ...
        svc.log("Reading file ...");
        .. some stuff...
        svc.log("Processing numbers ...");
        ... more stuff ...
        svc.log("Calculating power ...");
        ... and more stuff ...
    }
}

The log processing was too expensive, so I decided to use another thread to do the log process. First I created a new thread per each log operation. It was faster but I ran out memory. So I decided to create a Singleton thread that just log the messages. It's faster and use less memory, but now I have a new problem: the log is being written in other order... Sometimes I have

Calculating power...
Reading file...
Processing numbers ...

instead of

Reading file...
Processing numbers ...
Calculating power...

I tried using BlockingQueue, so instead log directly, I put the messages in the queue and then just read and log the messages in it, but I have the same problem with the order.

I have another idea: put the messages into a synchronized collection, specifying an order throug a variable and pop the elements depending on the variable, but it sounds weird.

Any ideas to keep using of threads and keep order insertion?

1 个答案:

答案 0 :(得分:0)

You can put the messages in a ConcurrentSkipListSet, which is thread-safe and will keep the elements ordered according to their natural order or else according to a comparator (e.g. their timestamp). There's also a ConcurrentSkipListMap that orders according to they keys' natural ordering.