多线程环境中的数据不一致

时间:2017-07-23 13:45:18

标签: java multithreading concurrency concurrenthashmap

我创建了一个应用程序,其中包含&写入远程文件。我在不同目录(A.propertiesB.propertiesC.properties)中有不同的文件(folder-1folder-2folder-3)。每个目录具有相同的文件名和不同的数据。

我已使用this other answer提供的LockRegistry在我的应用程序中实现了并发性。问题是如果一个线程正在访问A.properties而另一个线程访问B.properties,则显示给最终用户的propertyMap将包含来自属性文件的两个数据。我该如何解决这个问题?

我的代码:

public class UDEManager
{
    private Map<String, String> propertyMap  = new TreeMap<>();
    HttpSession session = null;

    public UDEPropertyManager()
    {
        super();
    }

    public void init(ServletConfig config) throws ServletException
    {
        super.init(config);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
    {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
    {
        // Code for calling thread for read/write operations into remote
        // file and fill the propertyMap
    }
}

class WebAppProperty implements Runnable
{
    private WebApp webapp; // folder-1
    private String propertyFile; // A.properties
    private String keyValue; //messages-title=Messages
    private LockType mode;

    public String getPropertyFile()
    {
        return propertyFile;
    }

    public void setPropertyFile(String propertyFile)
    {
        this.propertyFile = propertyFile;
    }

    @Override
    public void run()
    {
        try {
            LockRegistry.INSTANCE.acquire(propertyFile, mode);

            if (this.mode == LockType.WRITE) {
                writeToPropertyFile();
            } else if (this.mode == LockType.READ) {
                getProperty(this.webapp, this.propertyFile);
            }
        } catch (Exception ie) {
            sysoutAndLog("Thread is Interrupted");
            ie.printStackTrace();
        } finally {
            LockRegistry.INSTANCE.release(propertyFile, mode);
        }
    }

    private boolean getProperty(WebApp webapp, String property)
    {
        try {
            // read from file and put it into Map instance variable
            // of calling class (UDEManager)
            propertyMap.put(key, value);
        } catch(Exception e) {
            sysoutAndLog("Error while reading property ");
            e.printStackTrace();
        }
        return false;
    }

    private void writeToPropertyFile()
    {
        try {
            // Write data into remote file
        } catch (Exception e) {
            sysoutAndLog("exception while writing to file.");
            e.printStackTrace();
        }
    }
}

0 个答案:

没有答案
相关问题