Initialising your app using multithreading in Java

Viewed 51

I'm new to the whole multithreading in Java thing and I'm unable to get my head around something.

I'm trying to initialise my app properly using multithreading.

For example, I'm using a database (mongodb to be exact) and need to initialise a connection to it, then connect and check a collection exists and then read from it.

Once I have that, I will eventually have a list view (JavaFX) that will display the information taken from the database.

Ideally, whilst this is going on, I'd like other things to be done (in true mutlithreading style).

Would I need to put each submitted task into a queue of sorts and then iterate through, wait if they're not ready and then remove them once they're finished?

I've always done this singlethreaded and it's always been slow

Cheers

3 Answers

For such purpose you could add connection pool for your application.

Everything depends on configuration for your project.

The best is to make it configurable. When load is low just have ~4 connections (min) at pool. If load is increased it could go up till 20 (max).

Use an asynchronous MongoDB client like the high level ones mentioned here

  • MongoDB RxJava Driver (An RxJava implementation of the MongoDB Driver)
  • MongoDB Reactive Streams Java Driver (A Reactive Streams implementation for the JVM)

You need to coordinate partial tasks. If you represent tasks with threads, coordination can be done using semaphores and/or blocking queues.

More effective way is represent tasks as dataflow actors - they consume less memory, and you can generate all the tasks at the very start.

Related