Monday, November 17, 2008

Multiple Profiles running simultaneously synchronization in SeleniumJRunner

We must assign each SeleniumJRunner a unique profile name at one time.
Otherwise, if 2 instances use the same profile name at one time, Firefox will report "Firefox is already running..." error.

Assume we have pre-created Firefox profiles on one machine with name:
testprofile1
testprofile2
testprofile3
...
testprofile9

We can lock profile name when one SeleniumJRunner is using it and unlock it when SeleniumJRunner quit. If there is no free profile name, let new SeleniumJRunner wait.

Sample code:
public static String lockAndGetAvailableProfile(String[] allProfiles) { 
  FileLock lock = null; 
  for (int i = 0; i < allProfiles.length; i++) {
   try {
    RandomAccessFile raf = new RandomAccessFile(PROFILE_LOCK_FOLDER 
                        + "/" +i+".lck" , "rw");
    FileChannel fileChannel = raf.getChannel();
    lock = fileChannel.tryLock();
    if(lock != null && lock.isValid()
       && !lock.isShared()){ 
     return allProfiles[i];
    }else{
     lock = null;
     fileChannel.close();
     raf.close();
    }
   } catch (IOException ioe) {
    ioe.printStackTrace();
   } 
  }
  return "No available profile";
}

No comments:

Post a Comment