Многоядерное программирование на Java - PullRequest
0 голосов
/ 25 апреля 2018

Эта программа принимает входные файлы последовательно, но все задачи выполняются параллельно, используя одно ядро. Время выполнения для всех задач больше, чем время последовательного выполнения. Я хочу сократить время выполнения, используя несколько ядер, выполняя задачи параллельно. Как я могу это сделать? Как я могу использовать многоядерный в этой программе? Я хочу использовать как минимум два ядра.

package TestParallel;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

/**
 *
 * @author Sohel Rana
 */
public class Executor {

    public void encrypt(File fname) throws Exception {
        System.out.println("Encryption Started : " + System.currentTimeMillis() + " File Name : " + fname);
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(256);  //using AES-256
        SecretKey key = keyGen.generateKey();  //generating key
        //  System.out.println("Key = " + bytesToHex(key.getEncoded()));
        Cipher aesCipher = Cipher.getInstance("AES");  //getting cipher for AES
        aesCipher.init(Cipher.ENCRYPT_MODE, key);  //initializing cipher for encryption with key

        //creating file output stream to write to file
        try (FileOutputStream fos = new FileOutputStream(fname + ".aes")) {
            //creating object output stream to write objects to file
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(key);  //saving key to file for use during decryption

            //creating file input stream to read contents for encryption
            try (FileInputStream fis = new FileInputStream(fname)) {
                //creating cipher output stream to write encrypted contents
                try (CipherOutputStream cos = new CipherOutputStream(fos, aesCipher)) {
                    int read;
                    byte buf[] = new byte[4096];
                    while ((read = fis.read(buf)) != -1) //reading from file
                    {
                        cos.write(buf, 0, read);  //encrypting and writing to file
                    }
                }
            }
            System.out.print("\nComplete Time = " + System.currentTimeMillis());
            System.out.println(" \tand file task complete :" + fname);
            //  fname.delete();
        }

    }

    public static void main(final String[] args) throws InterruptedException {
        // final ExecutorService pool = Executors.newFixedThreadPool(4);
        int cores = Runtime.getRuntime().availableProcessors();
        System.out.println("Available processor cores is " + cores);
        File file1 = new File("C:\\Users\\Sohel Rana\\Desktop\\test\\Khushnuma Official Video HD - Suyyash Rai & Kishwer Merchant_HD.mp4");
        File file2 = new File("C:\\Users\\Sohel Rana\\Desktop\\test\\EK MULAQAT - Sonali Cable HD.mp4");
        File file3 = new File("C:\\Users\\Sohel Rana\\Desktop\\test\\Java Cryptography Tutorials 1 AES Encryption and Decryption using Java.mp4");
        File file4 = new File("C:\\Users\\Sohel Rana\\Desktop\\test\\01. Nath Nath.MP4");

        Executor ex = new Executor();
        final ExecutorService executor = Executors.newFixedThreadPool(cores);
        long startTime = System.currentTimeMillis();
        for (File f : new File[]{file1, file2, file3, file4}) {
            startTime = System.currentTimeMillis();
            executor.execute(() -> {
                try {
                    ex.encrypt(f);
                    //System.out.println(f);
                } catch (Exception ex1) {
                    Logger.getLogger(Executor.class.getName()).log(Level.SEVERE, null, ex1);

                }
            });
        }

        executor.shutdown();

        if (executor.awaitTermination(1, TimeUnit.DAYS)) {
        } else {
            executor.shutdownNow();
        }
        long endTime = System.currentTimeMillis();

        System.out.println("\nParalle Execution Time : " + (endTime - startTime)
                + " milliseconds.");

    }
}

1 Ответ

0 голосов
/ 25 апреля 2018

Здесь есть случай обработки InputStream в OutputStream. Для этого можно использовать java nio Piped I / O , с двумя потоками . Это экономит блокировку на чтение и запись.

executor.shutdown(); после цикла for кажется преждевременным.

Остальное в порядке.

Возможно, ваш вопрос направлен на использование физических ядер в JVM. Последнее, что я знал, Linux на данный момент лучше, чем Windows, но я вполне могу ошибаться.

...