Skip to content
Advertisement

sorting files using multithreading in java

I was given an assignment to write all ordered contents of given files into a result.txt. At first, the filenames are split into different Arraylists where each file contains a label in a format #n/N where N is the total number of files. e.g.

British explorer James Clark Ross led the first expedition to reach the north magnetic pole #001/004

from a file 1831-06-01.txt

The problem with my code is that it has written in order 1,4,2,3 respectively. However, the result must be in order 1,2,3,4. This may be due to a lack of synchronization. Nonetheless, I am still struggling to fix the problem.

This is my code:

JavaScript

( NOTE: The class q4 cannot be altered)

Advertisement

Answer

This assignment is horrible. You have my sympathy.


Your two threads will have to communicate with each other. Each thread will have to know, what is the filename that the other thread wants to output next. And, they will have to take turns. Each thread needs to loop:

  1. While the date on my next file is less than or equal to the date on the other thread’s next file, output my next file,

  2. Tell the other thread, “it’s your turn,”

  3. If I have no more files, then exit (return from the run() method), otherwise, wait for the other thread to tell me it’s my turn again,

  4. Go back to step 1.

Having to take turns is the worst part of the assignment. Any time you find yourself needing to make threads take turns doing something—any time you need to make threads do things in a particular order—that’s a clear sign that all of the things should be done by a single thread.


The only way threads can communicate is through shared variables. Your instructor has done you a huge disservice by telling you not to modify the q4 class. That prevents you from passing any shared objects in to your PopThread implementation through its constructor.

The only other way your two threads can share any variables is by making the variables static. Forcing you to use static is the second worst part of the assignment. If you go on to study software engineering, you will learn that static is an anti-pattern. Programs that use static variables are brittle (i.e., hard to modify), and they are hard to test.

Forcing you to use static variables also will make your threads do extra work to figure out who is who. Normally, I would do something like this so that each thread would automatically know which state is its own, and which belongs to the other guy:

JavaScript

The best way I can think of with static variables would be to have an array of two SharedState, and have the threads use an AtomicInteger to each assign themself one of the two array slots:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement