Статьи

Игра с параллелизмом Java

Недавно мне нужно было преобразовать некоторый файл, каждый из которых имеет список (массив) объектов в формате JSON, в файлы, каждый из которых имеет отдельные строки одних и тех же данных (объектов). Это было одноразовое и простое задание. Я делал чтение и запись, используя некоторые функции Java nio. Я использовал GSON самым простым способом. Один поток работает над файлами, конвертирует и записывает. Вся операция закончилась за несколько секунд. Однако я хотел немного поиграть с параллелизмом. Поэтому я усовершенствовал инструмент для одновременной работы.

Потоки

Runnable для чтения файла.

Потоки читателей отправляются в ExecutorService. Вывод, представляющий собой список объектов (в данном случае пользователя), будет помещен в BlockingQueue.

Runnable для записи файла.

Каждый работающий будет опрашивать из очереди блокировки. Он будет записывать строки данных в файл. Я не добавляю писатель Runnable в ExecutorService, но вместо этого просто запускаю поток с ним. У runnable есть шаблон while(some boolen is true) {...} . Подробнее об этом ниже …

Синхронизация всего

BlockingQueue — это интерфейс потоков обоих типов. Поскольку работающий писатель работает в цикле while (потребитель), я хотел иметь возможность остановить его, чтобы инструмент завершился. Для этого я использовал два объекта:

семафор

Цикл, который читает входные файлы, увеличивает счетчик. Как только я закончил обход входных файлов и отправил авторов, я инициализировал семафор в основном потоке: semaphore.acquire(numberOfFiles);

В каждом из доступных читателей я выпускал семафор: semaphore.release();

AtomicBoolean

Цикл while авторов использует AtomicBoolean. Пока AtomicBoolean == true, писатель будет продолжать. В основном потоке, сразу после получения семафора, я установил для AtomicBoolean значение false. Это позволяет завершать потоки записи.

Использование Java NIO

Для сканирования, чтения и записи файловой системы я использовал некоторые функции Java NIO.

Сканирование: Files.newDirectoryStream(inputFilesDirectory, "*.json");
Удаление выходного каталога перед запуском: Files.walkFileTree...
BufferedReader и BufferedWriter: Files.newBufferedReader(filePath); Files.newBufferedWriter(fileOutputPath, Charset.defaultCharset());

Одна запись. Для генерации случайных файлов для этого примера я использовал apache commons lang: RandomStringUtils.randomAlphabetic
Весь код в GitHub .

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
public class JsonArrayToJsonLines {
    private final static Path inputFilesDirectory = Paths.get("src\\main\\resources\\files");
    private final static Path outputDirectory = Paths
            .get("src\\main\\resources\\files\\output");
    private final static Gson gson = new Gson();
     
    private final BlockingQueue<EntitiesData> entitiesQueue = new LinkedBlockingQueue<>();
     
    private AtomicBoolean stillWorking = new AtomicBoolean(true);
    private Semaphore semaphore = new Semaphore(0);
    int numberOfFiles = 0;
 
    private JsonArrayToJsonLines() {
    }
 
    public static void main(String[] args) throws IOException, InterruptedException {
        new JsonArrayToJsonLines().process();
    }
 
    private void process() throws IOException, InterruptedException {
        deleteFilesInOutputDir();
        final ExecutorService executorService = createExecutorService();
        DirectoryStream<Path> directoryStream = Files.newDirectoryStream(inputFilesDirectory, "*.json");
         
        for (int i = 0; i < 2; i++) {
            new Thread(new JsonElementsFileWriter(stillWorking, semaphore, entitiesQueue)).start();
        }
 
        directoryStream.forEach(new Consumer<Path>() {
            @Override
            public void accept(Path filePath) {
                numberOfFiles++;
                executorService.submit(new OriginalFileReader(filePath, entitiesQueue));
            }
        });
         
        semaphore.acquire(numberOfFiles);
        stillWorking.set(false);
        shutDownExecutor(executorService);
    }
 
    private void deleteFilesInOutputDir() throws IOException {
        Files.walkFileTree(outputDirectory, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Files.delete(file);
                return FileVisitResult.CONTINUE;
            }
        });
    }
 
    private ExecutorService createExecutorService() {
        int numberOfCpus = Runtime.getRuntime().availableProcessors();
        return Executors.newFixedThreadPool(numberOfCpus);
    }
 
    private void shutDownExecutor(final ExecutorService executorService) {
        executorService.shutdown();
        try {
            if (!executorService.awaitTermination(120, TimeUnit.SECONDS)) {
                executorService.shutdownNow();
            }
 
            if (!executorService.awaitTermination(120, TimeUnit.SECONDS)) {
            }
        } catch (InterruptedException ex) {
            executorService.shutdownNow();
            Thread.currentThread().interrupt();
        }
    }
 
 
    private static final class OriginalFileReader implements Runnable {
        private final Path filePath;
        private final BlockingQueue<EntitiesData> entitiesQueue;
 
        private OriginalFileReader(Path filePath, BlockingQueue<EntitiesData> entitiesQueue) {
            this.filePath = filePath;
            this.entitiesQueue = entitiesQueue;
        }
 
        @Override
        public void run() {
            Path fileName = filePath.getFileName();
            try {
                BufferedReader br = Files.newBufferedReader(filePath);
                User[] entities = gson.fromJson(br, User[].class);
                System.out.println("---> " + fileName);
                entitiesQueue.put(new EntitiesData(fileName.toString(), entities));
            } catch (IOException | InterruptedException e) {
                throw new RuntimeException(filePath.toString(), e);
            }
        }
    }
 
    private static final class JsonElementsFileWriter implements Runnable {
        private final BlockingQueue<EntitiesData> entitiesQueue;
        private final AtomicBoolean stillWorking;
        private final Semaphore semaphore;
 
        private JsonElementsFileWriter(AtomicBoolean stillWorking, Semaphore semaphore,
                BlockingQueue<EntitiesData> entitiesQueue) {
            this.stillWorking = stillWorking;
            this.semaphore = semaphore;
            this.entitiesQueue = entitiesQueue;
        }
 
        @Override
        public void run() {
            while (stillWorking.get()) {
                try {
                    EntitiesData data = entitiesQueue.poll(100, TimeUnit.MILLISECONDS);
                    if (data != null) {
                        try {
                            String fileOutput = outputDirectory.toString() + File.separator + data.fileName;
                            Path fileOutputPath = Paths.get(fileOutput);
                            BufferedWriter writer = Files.newBufferedWriter(fileOutputPath, Charset.defaultCharset());
                            for (User user : data.entities) {
                                writer.append(gson.toJson(user));
                                writer.newLine();
                            }
                            writer.flush();
                            System.out.println("=======================================>>>>> " + data.fileName);
                        } catch (IOException e) {
                            throw new RuntimeException(data.fileName, e);
                        } finally {
                            semaphore.release();
                        }
                    }
                } catch (InterruptedException e1) {
                }
            }
        }
    }
 
    private static final class EntitiesData {
        private final String fileName;
        private final User[] entities;
 
        private EntitiesData(String fileName, User[] entities) {
            this.fileName = fileName;
            this.entities = entities;
        }
    }
}