どのように私はこのプログラムを設計する必要がありますか?

Nirmalyaシンハ:

私はJavaでプログラムを書いています。絵は自明です -

設計主な方法は3つのスレッドを生成します。SAXプロセッサは、入力XMLファイルを処理し、JAXBオブジェクトとグアバキャッシュを入れ、それらを生成します。グアバのキャッシュは、別のスレッドによって処理されます。任意のオブジェクトをキャッシュに出るたび、このスレッドを通知MDLジェネレータである第三のスレッドが(それは、同様のJAXBオブジェクト関連の相互接続にそれらをし、MDLと呼ばれる別のXMLファイルを生成します)。私は、メインクラスのために以下をコード化しています -

package test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MainClass {

    public static void main(String args[]) {

        ExecutorService xMLService = Executors.newFixedThreadPool(1);
        xMLService.execute(new XMLProcessor());

        ExecutorService cacheService = Executors.newFixedThreadPool(1);
        cacheService.execute(new CacheProcessor());

        ExecutorService mdlService = Executors.newFixedThreadPool(1);
        mdlService.execute(new MDLProcessor());

        xMLService.shutdown();
        cacheService.shutdown();
        mDLService.shutdown();
    }
}

But now I have doubts regarding how to pass objects between the threads and how to notify the MDL generator whenever a new object comes to the cache. In Java old threading model we could use notify(), but I want to use the current ExecutorService. And there are asynchronous callbacks. So I am wondering how to design this framework. How to pass objects and notify the threads? We are keeping the cache objects in HashMap and the CacheService thread needs to pass the key to the MDLService. So which pattern should I use?

Rahul R. :

ここで、上述の場合の実装例です。回答している他のいくつかで述べたように実装は、さえグアバキャッシュなしで可能だったかもしれないことに注意してください。それにもかかわらず、私はNirmalayaがそれを求めることについて正当な理由があったかもしれないと推測しました。私が考えることができることの一つな理由は、実行時のメモリ上に保存するために、ストレージ・デバイスまたはデータベースへのキャッシュのこぼれています。

従業員records.xml

<?xml version="1.0" encoding="UTF-8"?>
<Employees>
    <Employee id="1">
        <name>Thomas</name>
    </Employee>
    <Employee id="2">
        <name>Lisa</name>
    </Employee>
    <Employee id="3">
        <name>Ronald</name>
    </Employee>
    <Employee id="4">
        <name>Erica</name>
    </Employee>
</Employees>

Employee.java

package com.technoroy.examples.guava;

/**
 * A value holder POJO implementation for Employee records
 * @author Rahul R
 *
 */
class Employee {
    private Integer id = null;
    private String name = null;

    public Employee() {
        super();
    }

    public Employee(Integer id, String name) {
        super();
        this.id = id;
        this.name = name;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Employee [id=" + id + ", name=" + name + "]";
    }
}

GuavaCacheProcessor.java

package com.technoroy.examples.guava;

import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

/**
 * The primary executable class
 * 
 * @author Rahul R
 *
 */
public class GuavaCacheProcessor {
    private final static BlockingQueue<Integer> notificationQueue = new LinkedBlockingQueue<>();

    public static void main(String... arguments) {
        Runnable xmlProcessor = new Runnable() {
            public void run() {
                parseDataFile();
            }
        };

        Runnable mdlGenerator = new Runnable() {
            public void run() {
                try {
                    while (true) {
                        Integer id = notificationQueue.take();
                        Employee record = ApplicationCacheUtil.getRecord(id);
                        generateContent(record);
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        };

        ExecutorService executorService = Executors.newFixedThreadPool(2);
        executorService.submit(xmlProcessor);
        executorService.submit(mdlGenerator);
    }

    public static void generateContent(Employee employee) {
        System.out.println(employee);
    }

    public static void parseDataFile() {
        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        InputStream dataInputStream = GuavaCacheProcessor.class.getResourceAsStream("employee-records.xml");

        try {
            SAXParser saxParser = saxParserFactory.newSAXParser();
            saxParser.parse(dataInputStream, new DefaultHandler() {
                private Employee employee = null;
                private StringBuilder elementValue = null;

                @Override
                public void startElement(String uri, String localName, String qName, Attributes attributes)
                        throws SAXException {
                    if (qName.equalsIgnoreCase("Employee")) {
                        employee = new Employee();

                        String id = attributes.getValue("id");
                        if (id.matches("-?\\d+(\\.\\d+)?")) {
                            employee.setId(Integer.valueOf(id));
                        }
                    }

                    elementValue = new StringBuilder();
                }

                @Override
                public void characters(char ch[], int start, int length) throws SAXException {
                    if (elementValue != null) {
                        elementValue.append(new String(ch, start, length));
                    }
                }

                @Override
                public void endElement(String uri, String localName, String qName) throws SAXException {
                    if (qName.equalsIgnoreCase("name")) {
                        if (employee != null && elementValue != null) {
                            employee.setName(elementValue.toString());
                        }
                    } else if (qName.equalsIgnoreCase("Employee")) {
                        ApplicationCacheUtil.putRecord(employee.getId(), employee);
                        try {
                            notificationQueue.put(employee.getId());
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                    elementValue = null;
                }
            });
        } catch (ParserConfigurationException | SAXException | IOException e) {
            e.printStackTrace();
        }
    }
}

/**
 * The Cache utilities class, that initializes and returns a handle to the
 * cache.
 * 
 * @author Rahul R
 *
 */
class ApplicationCacheUtil {
    private static Cache<Integer, Employee> cache = CacheBuilder.newBuilder().build();

    public static Cache<Integer, Employee> getCache() {
        return cache;
    }

    public static void putRecord(Integer key, Employee value) {
        cache.put(key, value);
    }

    public static Employee getRecord(Integer key) {
        return cache.getIfPresent(key);
    }
}

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=173458&siteId=1