samedi 27 juin 2015

How do i unit test the following lock and multi-threaded code

I have the following write method which writes data to a file using gson.

private static final File CONFIG_FILE = new File("./config.json");; 
private static final ReadWriteLock READ_WRITE_LOCK = new ReentrantReadWriteLock(true);
private static final Lock READ_LOCK = READ_WRITE_LOCK.readLock();
private static final Lock WRITE_LOCK = READ_WRITE_LOCK.writeLock();
...
    public void write(JsonData data) {
    Verifier.verifyNotNull(data,"data : null");
    Verifier.verifyNotNull(data.getData(),"JsonData data : null");
    Verifier.verifyNotEmpty(data.getIdentifier(),"JsonData identifier : empty");

    Writer writer  = null;
    Gson gson = null;
      try {  
         WRITE_LOCK.lock();
         writer = new FileWriter(CONFIG_FILE);

         gson = new GsonBuilder().setPrettyPrinting().create();
         gson.toJson(data, writer);
      } 
      catch (IOException e) {  
           e.printStackTrace();  
      }  
      finally {
         try {
            writer.flush();
            writer.close();
            WRITE_LOCK.unlock();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }  
      }

The lock displayed above is Reeentrant lock provided by the Java libraries. If I want to unit test the above method which i want to be thread safe, how do it test it?

Please advise,

Thanks!

Aucun commentaire:

Enregistrer un commentaire