开发者

Multi-Threaded Application - Help with some pseudo code!

开发者 https://www.devze.com 2022-12-27 10:42 出处:网络
I am working on a multi-threaded application and need help with some pseudo-code. To make it simpler for implementation I will try to explain that in simple terms / test case.

I am working on a multi-threaded application and need help with some pseudo-code. To make it simpler for implementation I will try to explain that in simple terms / test case.

Here is the scenario -

I have an array list of strings (sa开发者_JAVA技巧y 100 strings)

I have a Reader Class that reads the strings and passes them to a Writer Class that prints the strings to the console. Right now this runs in a Single Thread Model.

I wanted to make this multi-threaded but with the following features -

Ability to set MAX_READERS

Ability to set MAX_WRITERS

Ability to set BATCH_SIZE

So basically the code should instantiate those many Readers and Writers and do the work in parallel.

Any pseudo code will really be helpful to keep me going!


This sounds like the classic consumer-producer problem. Have a look at Wikipedia's article about it. They have plenty of pseudo code there.


Aside from using the producer-consumer pattern that has been suggested, I would recommend that you use the CopyOnWriteArrayList so you can have lock-free read/write/iteration of your list. Since you're only working with a couple of hundred strings you will probably not have any performance issues with the CopyOnWriteArrayList.

If you're concerned about performance then I actually think it might be better if you use the BlockingQueue or a ConcurrentHashMap. They will allow you to maximize throughput with your multithreaded application.


The recommended option:
A BlockingQueue works very well with multiple producers and consumers, but of course it implies an order of data processing (FIFO). If you're OK with FIFO ordering, then you will probably find that the BlockingQueue is a faster and more robust option.


I think that the Wikipedia article has sufficient pseudo code for you to use, but you can also check out some of the following SO questions:
https://stackoverflow.com/search?q=java+producer+consumer

Java Producer-Consumer Designs:
Producer/Consumer threads using a Queue
design of a Producer/Consumer app

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号