001package net.minecraft.world.storage;
002
003import java.util.ArrayList;
004import java.util.Collections;
005import java.util.List;
006
007public class ThreadedFileIOBase implements Runnable
008{
009    /** Instance of ThreadedFileIOBase */
010    public static final ThreadedFileIOBase threadedIOInstance = new ThreadedFileIOBase();
011    private List threadedIOQueue = Collections.synchronizedList(new ArrayList());
012    private volatile long writeQueuedCounter = 0L;
013    private volatile long savedIOCounter = 0L;
014    private volatile boolean isThreadWaiting = false;
015
016    private ThreadedFileIOBase()
017    {
018        Thread thread = new Thread(this, "File IO Thread");
019        thread.setPriority(1);
020        thread.start();
021    }
022
023    public void run()
024    {
025        while (true)
026        {
027            this.processQueue();
028        }
029    }
030
031    /**
032     * Process the items that are in the queue
033     */
034    private void processQueue()
035    {
036        for (int i = 0; i < this.threadedIOQueue.size(); ++i)
037        {
038            IThreadedFileIO ithreadedfileio = (IThreadedFileIO)this.threadedIOQueue.get(i);
039            boolean flag = ithreadedfileio.writeNextIO();
040
041            if (!flag)
042            {
043                this.threadedIOQueue.remove(i--);
044                ++this.savedIOCounter;
045            }
046
047            try
048            {
049                Thread.sleep(this.isThreadWaiting ? 0L : 10L);
050            }
051            catch (InterruptedException interruptedexception)
052            {
053                interruptedexception.printStackTrace();
054            }
055        }
056
057        if (this.threadedIOQueue.isEmpty())
058        {
059            try
060            {
061                Thread.sleep(25L);
062            }
063            catch (InterruptedException interruptedexception1)
064            {
065                interruptedexception1.printStackTrace();
066            }
067        }
068    }
069
070    /**
071     * threaded io
072     */
073    public void queueIO(IThreadedFileIO par1IThreadedFileIO)
074    {
075        if (!this.threadedIOQueue.contains(par1IThreadedFileIO))
076        {
077            ++this.writeQueuedCounter;
078            this.threadedIOQueue.add(par1IThreadedFileIO);
079        }
080    }
081
082    public void waitForFinish() throws InterruptedException
083    {
084        this.isThreadWaiting = true;
085
086        while (this.writeQueuedCounter != this.savedIOCounter)
087        {
088            Thread.sleep(10L);
089        }
090
091        this.isThreadWaiting = false;
092    }
093}