Example usage for java.util.concurrent CopyOnWriteArrayList CopyOnWriteArrayList

List of usage examples for java.util.concurrent CopyOnWriteArrayList CopyOnWriteArrayList

Introduction

In this page you can find the example usage for java.util.concurrent CopyOnWriteArrayList CopyOnWriteArrayList.

Prototype

public CopyOnWriteArrayList() 

Source Link

Document

Creates an empty list.

Usage

From source file:com.l2jfree.gameserver.model.entity.events.DM.java

public static void cleanDM() {
    for (L2Player player : _players) {
        removePlayer(player);//from w ww. ja  v a 2  s  . co m
    }

    _savePlayers = new CopyOnWriteArrayList<String>();
    _topPlayer = null;
    _npcSpawn = null;
    _joining = false;
    _teleport = false;
    _started = false;
    _sitForced = false;
    _topKills = 0;
    _players = new CopyOnWriteArrayList<L2Player>();

}

From source file:org.opendaylight.snmp4sdn.internal.TopologyServiceShim.java

@Override
public void nodeConnectorUpdated(String containerName, NodeConnector p, UpdateType t) {
    if (this.containerMap == null) {
        logger.error("containerMap is NULL");
        return;//from   www  .  j  a v  a2 s .c  om
    }
    List<String> containers = this.containerMap.get(p);
    if (containers == null) {
        containers = new CopyOnWriteArrayList<String>();
    }
    boolean updateMap = false;
    switch (t) {
    case ADDED:
        if (!containers.contains(containerName)) {
            containers.add(containerName);
            updateMap = true;
        }
        break;
    case REMOVED:
        if (containers.contains(containerName)) {
            containers.remove(containerName);
            updateMap = true;
            removeNodeConnector(containerName, p);
        }
        break;
    case CHANGED:
        break;
    }
    if (updateMap) {
        if (containers.isEmpty()) {
            // Do cleanup to reduce memory footprint if no
            // elements to be tracked
            this.containerMap.remove(p);
        } else {
            this.containerMap.put(p, containers);
        }
    }
}

From source file:org.kie.server.services.impl.KieServerImpl.java

public ServiceResponse<KieContainerResource> deactivateContainer(String containerId) {

    List<Message> messages = new CopyOnWriteArrayList<Message>();
    try {/*from ww  w.  j av a2s  .  c o  m*/
        KieContainerInstanceImpl kci = context.getContainer(containerId);
        if (kci != null && kci.getStatus().equals(KieContainerStatus.STARTED)) {

            synchronized (kci) {
                eventSupport.fireBeforeContainerDeactivated(this, kci);

                Map<String, Object> parameters = getContainerParameters(
                        kci.getKieContainer().getContainerReleaseId(), messages);
                // process server extensions
                List<KieServerExtension> extensions = context.getServerExtensions();
                for (KieServerExtension extension : extensions) {
                    extension.deactivateContainer(containerId, kci, parameters);
                    logger.debug("Container {} (for release id {}) {} deactivation: DONE", containerId,
                            kci.getKieContainer().getContainerReleaseId(), extension);
                }

                kci.setStatus(KieContainerStatus.DEACTIVATED);

                // store the current state of the server
                storeServerState(currentState -> {
                    currentState.getContainers().forEach(containerResource -> {
                        if (containerId.equals(containerResource.getContainerId())) {
                            containerResource.setStatus(KieContainerStatus.DEACTIVATED);
                        }
                    });
                });

                eventSupport.fireAfterContainerDeactivated(this, kci);

                messages.add(
                        new Message(Severity.INFO, "Container " + containerId + " deactivated successfully."));
                return new ServiceResponse<KieContainerResource>(ServiceResponse.ResponseType.SUCCESS,
                        "Container " + containerId + " deactivated successfully.", kci.getResource());
            }
        } else {
            messages.add(new Message(Severity.ERROR,
                    "Container " + containerId + " not found or not in started status."));
            return new ServiceResponse<KieContainerResource>(ServiceResponse.ResponseType.FAILURE,
                    "Container " + containerId + " not found or not in started status.");
        }
    } catch (Exception e) {
        messages.add(new Message(Severity.ERROR,
                "Error deactivating container '" + containerId + "' due to " + e.getMessage()));
        logger.error("Error deactivating Container '" + containerId + "'", e);
        return new ServiceResponse<KieContainerResource>(ServiceResponse.ResponseType.FAILURE,
                "Error deactivating container " + containerId + ": " + e.getClass().getName() + ": "
                        + e.getMessage());
    } finally {
        this.containerMessages.put(containerId, messages);
    }
}

From source file:com.app.server.WarDeployer.java

/**
 * This method deploys the war in exploded form and configures it.
 * /* w w w.ja v  a2s  . c  o m*/
 * @param file
 * @param customClassLoader
 * @param warDirectoryPath
 */
public void extractWar(File file, ClassLoader classLoader) {

    StringBuffer classPath = new StringBuffer();
    int numBytes;
    WebClassLoader customClassLoader = null;
    CopyOnWriteArrayList<URL> jarUrls = new CopyOnWriteArrayList<URL>();
    try {
        ConcurrentHashMap jspMap = new ConcurrentHashMap();
        ZipFile zip = new ZipFile(file);
        ZipEntry ze = null;
        // String fileName=file.getName();
        String directoryName = file.getName();
        directoryName = directoryName.substring(0, directoryName.indexOf('.'));
        try {
            /*ClassLoader classLoader = Thread.currentThread()
                  .getContextClassLoader();*/
            // log.info("file://"+warDirectoryPath+"/WEB-INF/classes/");
            jarUrls.add(new URL("file:" + scanDirectory + "/" + directoryName + "/WEB-INF/classes/"));
            // new WebServer().addURL(new
            // URL("file://"+warDirectoryPath+"/"),customClassLoader);
        } catch (Exception e) {
            log.error("syntax of the URL is incorrect", e);
            //e1.printStackTrace();
        }
        String fileDirectory;
        Enumeration<? extends ZipEntry> entries = zip.entries();
        while (entries.hasMoreElements()) {
            ze = entries.nextElement();
            // //log.info("Unzipping " + ze.getName());
            String filePath = scanDirectory + "/" + directoryName + "/" + ze.getName();
            if (!ze.isDirectory()) {
                fileDirectory = filePath.substring(0, filePath.lastIndexOf('/'));
            } else {
                fileDirectory = filePath;
            }
            // //log.info(fileDirectory);
            createDirectory(fileDirectory);
            if (!ze.isDirectory()) {
                FileOutputStream fout = new FileOutputStream(filePath);
                byte[] inputbyt = new byte[8192];
                InputStream istream = zip.getInputStream(ze);
                while ((numBytes = istream.read(inputbyt, 0, inputbyt.length)) >= 0) {
                    fout.write(inputbyt, 0, numBytes);
                }
                fout.close();
                istream.close();
                if (ze.getName().endsWith(".jsp")) {
                    jspMap.put(ze.getName(), filePath);
                } else if (ze.getName().endsWith(".jar")) {
                    jarUrls.add(new URL("file:///" + scanDirectory + "/" + directoryName + "/" + ze.getName()));
                    classPath.append(filePath);
                    classPath.append(";");
                }
            }
        }
        zip.close();
        Set jsps = jspMap.keySet();
        Iterator jspIterator = jsps.iterator();
        classPath.append(scanDirectory + "/" + directoryName + "/WEB-INF/classes;");
        jarUrls.add(new URL("file:" + scanDirectory + "/" + directoryName + "/WEB-INF/classes/;"));
        ArrayList<String> jspFiles = new ArrayList();
        // log.info(classPath.toString());
        if (jspIterator.hasNext()) {
            jarUrls.add(new URL("file:" + scanDirectory + "/temp/" + directoryName + "/"));
            customClassLoader = new WebClassLoader(jarUrls.toArray(new URL[jarUrls.size()]), classLoader);
            while (jspIterator.hasNext()) {
                String filepackageInternal = (String) jspIterator.next();
                String filepackageInternalTmp = filepackageInternal;
                if (filepackageInternal.lastIndexOf('/') == -1) {
                    filepackageInternal = "";
                } else {
                    filepackageInternal = filepackageInternal.substring(0, filepackageInternal.lastIndexOf('/'))
                            .replace("/", ".");
                    filepackageInternal = "." + filepackageInternal;
                }
                createDirectory(scanDirectory + "/temp/" + directoryName);
                File jspFile = new File((String) jspMap.get(filepackageInternalTmp));
                String fName = jspFile.getName();
                String fileNameWithoutExtension = fName.substring(0, fName.lastIndexOf(".jsp")) + "_jsp";
                // String fileCreated=new JspCompiler().compileJsp((String)
                // jspMap.get(filepackageInternalTmp),
                // scanDirectory+"/temp/"+fileName,
                // "com.app.server"+filepackageInternal,classPath.toString());
                synchronized (customClassLoader) {
                    String fileNameInWar = filepackageInternalTmp;
                    jspFiles.add(fileNameInWar.replace("/", "\\"));
                    if (fileNameInWar.contains("/") || fileNameInWar.contains("\\")) {
                        customClassLoader.addURL("/" + fileNameInWar.replace("\\", "/"),
                                "com.app.server" + filepackageInternal.replace("WEB-INF", "WEB_002dINF") + "."
                                        + fileNameWithoutExtension);
                    } else {
                        customClassLoader.addURL("/" + fileNameInWar,
                                "com.app.server" + filepackageInternal.replace("WEB-INF", "WEB_002dINF") + "."
                                        + fileNameWithoutExtension);
                    }
                }
            }
        } else {
            customClassLoader = new WebClassLoader(jarUrls.toArray(new URL[jarUrls.size()]), classLoader);
        }
        String filePath = file.getAbsolutePath();
        // log.info("filePath"+filePath);
        filePath = filePath.substring(0, filePath.toLowerCase().lastIndexOf(".war"));
        urlClassLoaderMap.put(filePath.replace("\\", "/"), customClassLoader);
        if (jspFiles.size() > 0) {
            ClassLoader oldCL = Thread.currentThread().getContextClassLoader();
            //Thread.currentThread().setContextClassLoader(customClassLoader);
            String classPathBefore = "";
            try {
                JspCompiler jspc = new JspCompiler();
                jspc.setUriroot(scanDirectory + "/" + directoryName);
                jspc.setAddWebXmlMappings(false);
                jspc.setListErrors(false);
                jspc.setCompile(true);
                jspc.setOutputDir(scanDirectory + "/temp/" + directoryName + "/");
                jspc.setPackage("com.app.server");
                StringBuffer buffer = new StringBuffer();
                for (String jspFile : jspFiles) {
                    buffer.append(",");
                    buffer.append(jspFile);
                }
                String jsp = buffer.toString();
                jsp = jsp.substring(1, jsp.length());
                //log.info(jsp);
                classPathBefore = System.getProperty("java.class.path");
                System.setProperty("java.class.path",
                        System.getProperty("java.class.path") + ";" + classPath.toString().replace("/", "\\"));
                //jspc.setClassPath(System.getProperty("java.class.path")+";"+classPath.toString().replace("/", "\\"));
                jspc.setJspFiles(jsp);
                jspc.initCL(customClassLoader);
                jspc.execute();
                //jspc.closeClassLoader();
                //jspc.closeClassLoader();
            } catch (Throwable je) {
                log.error("Error in compiling the jsp page", je);
                //je.printStackTrace();
            } finally {
                System.setProperty("java.class.path", classPathBefore);
                //Thread.currentThread().setContextClassLoader(oldCL);
            }
            //Thread.currentThread().setContextClassLoader(customClassLoader);
        }
        try {
            File execxml = new File(scanDirectory + "/" + directoryName + "/WEB-INF/" + "executorservices.xml");
            if (execxml.exists()) {
                new ExecutorServicesConstruct().getExecutorServices(serverdigester, executorServiceMap, execxml,
                        customClassLoader);
            }
        } catch (Exception e) {
            log.error("error in getting executor services ", e);
            // e.printStackTrace();
        }
        try {
            File messagingxml = new File(
                    scanDirectory + "/" + directoryName + "/WEB-INF/" + "messagingclass.xml");
            if (messagingxml.exists()) {
                new MessagingClassConstruct().getMessagingClass(messagedigester, messagingxml,
                        customClassLoader, messagingClassMap);
            }
        } catch (Exception e) {
            log.error("Error in getting the messaging classes ", e);
            // e.printStackTrace();
        }
        webxmldigester.setNamespaceAware(true);
        webxmldigester.setValidating(true);
        // digester.setRules(null);
        FileInputStream webxml = new FileInputStream(
                scanDirectory + "/" + directoryName + "/WEB-INF/" + "web.xml");
        InputSource is = new InputSource(webxml);
        try {
            //log.info("SCHEMA");
            synchronized (webxmldigester) {
                // webxmldigester.set("config/web-app_2_4.xsd");
                WebAppConfig webappConfig = (WebAppConfig) webxmldigester.parse(is);
                servletMapping.put(scanDirectory + "/" + directoryName.replace("\\", "/"), webappConfig);
            }
            webxml.close();
        } catch (Exception e) {
            log.error("Error in pasrsing the web.xml", e);
            //e.printStackTrace();
        }
        //customClassLoader.close();
        // ClassLoaderUtil.closeClassLoader(customClassLoader);

    } catch (Exception ex) {
        log.error("Error in Deploying war " + file.getAbsolutePath(), ex);
    }
}

From source file:com.l2jfree.gameserver.model.entity.events.TvT.java

private static boolean startEventOk() {
    if (_joining || !_teleport || _started)
        return false;

    if (Config.TVT_EVEN_TEAMS.equals("NO") || Config.TVT_EVEN_TEAMS.equals("BALANCE")) {
        if (_teamPlayersCount.contains(0))
            return false;
    } else if (Config.TVT_EVEN_TEAMS.equals("SHUFFLE")) {
        CopyOnWriteArrayList<L2Player> playersShuffleTemp = new CopyOnWriteArrayList<L2Player>();
        int loopCount = 0;

        loopCount = _playersShuffle.size();

        for (int i = 0; i < loopCount; i++) {
            if (_playersShuffle != null)
                playersShuffleTemp.add(_playersShuffle.get(i));
        }/*  www .ja v  a2s.c om*/

        _playersShuffle = playersShuffleTemp;
        playersShuffleTemp.clear();

        //  if (_playersShuffle.size() < (_teams.size()*2)){
        //     return false;
        //  }
    }

    return true;
}

From source file:net.ymate.platform.core.lang.TreeObject.java

public TreeObject add(TreeObject tObject) {
    if (tObject != null) {
        if (_mode != MODE_MAP) {
            if (_mode == MODE_VALUE) {
                _type = TYPE_TREE_OBJECT;
                _mode = MODE_ARRAY;/*from   w ww  .j  av a  2 s .co m*/
            }
            if (_object == null) {
                // ?
                _object = new CopyOnWriteArrayList<TreeObject>();
            }
            ((List<TreeObject>) _object).add(tObject);
        } else {
            throw new IllegalStateException();
        }
    }
    return this;
}

From source file:org.apache.servicemix.http.ConsumerEndpointTest.java

public void testHttpInOutUnderLoad() throws Exception {
    final int nbThreads = 16;
    final int nbRequests = 8;
    final int endpointTimeout = 100;
    final int echoSleepTime = 90;
    final int soTimeout = 60 * 1000 * 1000;
    final int listenerTimeout = 5000;

    ExchangeCompletedListener listener = new ExchangeCompletedListener(listenerTimeout);
    container.addListener(listener);//from www .j  a  va 2s  . c  o  m

    HttpComponent http = new HttpComponent();
    //http.getConfiguration().setJettyConnectorClassName(SocketConnector.class.getName());
    HttpConsumerEndpoint ep = new HttpConsumerEndpoint();
    ep.setService(new QName("urn:test", "svc"));
    ep.setEndpoint("ep");
    ep.setTargetService(new QName("urn:test", "echo"));
    ep.setLocationURI("http://localhost:8192/ep1/");
    ep.setTimeout(endpointTimeout);
    http.setEndpoints(new HttpEndpointType[] { ep });
    container.activateComponent(http, "http");

    final CountDownLatch latchRecv = new CountDownLatch(nbThreads * nbRequests);
    EchoComponent echo = new EchoComponent() {
        protected boolean transform(MessageExchange exchange, NormalizedMessage in, NormalizedMessage out)
                throws MessagingException {
            latchRecv.countDown();
            try {
                Thread.sleep(echoSleepTime);
            } catch (InterruptedException e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            }
            out.setContent(in.getContent());
            return true;
        }
    };
    echo.setService(new QName("urn:test", "echo"));
    echo.setEndpoint("endpoint");
    container.activateComponent(echo, "echo");

    ((ExecutorFactoryImpl) container.getExecutorFactory()).getDefaultConfig().setMaximumPoolSize(16);

    container.start();

    final List<Throwable> throwables = new CopyOnWriteArrayList<Throwable>();
    final CountDownLatch latchSent = new CountDownLatch(nbThreads * nbRequests);
    for (int t = 0; t < nbThreads; t++) {
        new Thread() {
            public void run() {
                final SourceTransformer transformer = new SourceTransformer();
                final HttpClient client = new HttpClient();
                client.getParams().setSoTimeout(soTimeout);
                for (int i = 0; i < nbRequests; i++) {
                    try {
                        PostMethod post = new PostMethod("http://localhost:8192/ep1/");
                        post.setRequestEntity(new StringRequestEntity("<hello>world</hello>"));
                        client.executeMethod(post);
                        if (post.getStatusCode() != 200) {
                            throw new InvalidStatusResponseException(post.getStatusCode());
                        }
                        Node node = transformer.toDOMNode(new StreamSource(post.getResponseBodyAsStream()));
                        log.info(transformer.toString(node));
                        assertEquals("world", textValueOfXPath(node, "/hello/text()"));
                    } catch (Throwable t) {
                        throwables.add(t);
                    } finally {
                        latchSent.countDown();
                        //System.out.println("[" + System.currentTimeMillis() + "] Request " + latch.getCount() + " processed");
                    }
                }
            }
        }.start();
    }
    latchSent.await();
    latchRecv.await();
    listener.assertExchangeCompleted();
    for (Throwable t : throwables) {
        t.printStackTrace();
    }
}

From source file:com.cisco.oss.foundation.http.netlifx.apache.ApacheNetflixHttpClient.java

private InternalServerProxyMetadata loadServersMetadataConfiguration() {

    Configuration subset = ConfigurationFactory.getConfiguration().subset(getApiName());
    final Iterator<String> keysIterator = subset.getKeys();

    // read default values
    int readTimeout = subset.getInt("http." + LoadBalancerConstants.READ_TIME_OUT,
            LoadBalancerConstants.DEFAULT_READ_TIMEOUT);
    int connectTimeout = subset.getInt("http." + LoadBalancerConstants.CONNECT_TIME_OUT,
            LoadBalancerConstants.DEFAULT_CONNECT_TIMEOUT);
    long waitingTime = subset.getLong("http." + LoadBalancerConstants.WAITING_TIME,
            LoadBalancerConstants.DEFAULT_WAITING_TIME);
    int numberOfAttempts = subset.getInt("http." + LoadBalancerConstants.NUMBER_OF_ATTEMPTS,
            LoadBalancerConstants.DEFAULT_NUMBER_OF_ATTEMPTS);
    long retryDelay = subset.getLong("http." + LoadBalancerConstants.RETRY_DELAY,
            LoadBalancerConstants.DEFAULT_RETRY_DELAY);

    long idleTimeout = subset.getLong("http." + LoadBalancerConstants.IDLE_TIME_OUT,
            LoadBalancerConstants.DEFAULT_IDLE_TIMEOUT);
    int maxConnectionsPerAddress = subset.getInt("http." + LoadBalancerConstants.MAX_CONNECTIONS_PER_ADDRESS,
            LoadBalancerConstants.DEFAULT_MAX_CONNECTIONS_PER_ADDRESS);
    int maxConnectionsTotal = subset.getInt("http." + LoadBalancerConstants.MAX_CONNECTIONS_TOTAL,
            LoadBalancerConstants.DEFAULT_MAX_CONNECTIONS_TOTAL);
    int maxQueueSizePerAddress = subset.getInt("http." + LoadBalancerConstants.MAX_QUEUE_PER_ADDRESS,
            LoadBalancerConstants.DEFAULT_MAX_QUEUE_PER_ADDRESS);
    boolean followRedirects = subset.getBoolean("http." + LoadBalancerConstants.FOLLOW_REDIRECTS, false);
    boolean disableCookies = subset.getBoolean("http." + LoadBalancerConstants.DISABLE_COOKIES, false);
    boolean autoCloseable = subset.getBoolean("http." + LoadBalancerConstants.AUTO_CLOSEABLE, true);
    boolean autoEncodeUri = subset.getBoolean("http." + LoadBalancerConstants.AUTO_ENCODE_URI, true);
    boolean staleConnectionCheckEnabled = subset
            .getBoolean("http." + LoadBalancerConstants.IS_STALE_CONN_CHECK_ENABLED, false);
    boolean serviceDirectoryEnabled = subset
            .getBoolean("http." + LoadBalancerConstants.SERVICE_DIRECTORY_IS_ENABLED, false);
    String serviceName = subset.getString("http." + LoadBalancerConstants.SERVICE_DIRECTORY_SERVICE_NAME,
            "UNKNOWN");

    String keyStorePath = subset.getString("http." + LoadBalancerConstants.KEYSTORE_PATH, "");
    String keyStorePassword = subset.getString("http." + LoadBalancerConstants.KEYSTORE_PASSWORD, "");
    String trustStorePath = subset.getString("http." + LoadBalancerConstants.TRUSTSTORE_PATH, "");
    String trustStorePassword = subset.getString("http." + LoadBalancerConstants.TRUSTSTORE_PASSWORD, "");
    startEurekaClient = subset.getBoolean("http.startEurekaClient", true);

    final List<String> keys = new ArrayList<String>();

    while (keysIterator.hasNext()) {
        String key = keysIterator.next();
        keys.add(key);/*from   w w  w .j  a v a  2s  .  c o m*/
    }

    Collections.sort(keys);

    List<Pair<String, Integer>> hostAndPortPairs = new CopyOnWriteArrayList<Pair<String, Integer>>();

    for (String key : keys) {

        if (key.contains(LoadBalancerConstants.HOST)) {

            String host = subset.getString(key);

            // trim the host name
            if (org.apache.commons.lang.StringUtils.isNotEmpty(host)) {
                host = host.trim();
            }
            final String portKey = key.replace(LoadBalancerConstants.HOST, LoadBalancerConstants.PORT);
            if (subset.containsKey(portKey)) {
                int port = subset.getInt(portKey);
                // save host and port for future creation of server list
                hostAndPortPairs.add(Pair.of(host, port));
            }
        }

    }

    InternalServerProxyMetadata metadata = new InternalServerProxyMetadata(readTimeout, connectTimeout,
            idleTimeout, maxConnectionsPerAddress, maxConnectionsTotal, maxQueueSizePerAddress, waitingTime,
            numberOfAttempts, retryDelay, hostAndPortPairs, keyStorePath, keyStorePassword, trustStorePath,
            trustStorePassword, followRedirects, autoCloseable, staleConnectionCheckEnabled, disableCookies,
            serviceDirectoryEnabled, serviceName, autoEncodeUri);
    //        metadata.getHostAndPortPairs().addAll(hostAndPortPairs);
    //        metadata.setReadTimeout(readTimeout);
    //        metadata.setConnectTimeout(connectTimeout);
    //        metadata.setNumberOfRetries(numberOfAttempts);
    //        metadata.setRetryDelay(retryDelay);
    //        metadata.setWaitingTime(waitingTime);

    return metadata;

}

From source file:org.opendaylight.controller.protocol_plugin.openflow.internal.TopologyServiceShim.java

@Override
public void nodeConnectorUpdated(String containerName, NodeConnector p, UpdateType t) {
    if (this.containerMap == null) {
        logger.error("containerMap is NULL");
        return;/*from  w  w w.  java  2s  .c om*/
    }
    List<String> containers = this.containerMap.get(p);
    if (containers == null) {
        containers = new CopyOnWriteArrayList<String>();
    }
    switch (t) {
    case ADDED:
        if (!containers.contains(containerName)) {
            containers.add(containerName);
            updateContainerMap(containers, p);
            addNodeConnector(containerName, p);
        }
        break;
    case REMOVED:
        if (containers.contains(containerName)) {
            containers.remove(containerName);
            updateContainerMap(containers, p);
            removeNodeConnector(containerName, p);
        }
        break;
    case CHANGED:
        break;
    }
}

From source file:io.realm.Realm.java

private static void validateAgainstExistingConfigurations(RealmConfiguration newConfiguration) {

    // Ensure cache state
    String realmPath = newConfiguration.getPath();
    List<RealmConfiguration> pathConfigurationCache = globalPathConfigurationCache.get(realmPath);
    if (pathConfigurationCache == null) {
        pathConfigurationCache = new CopyOnWriteArrayList<RealmConfiguration>();
        globalPathConfigurationCache.put(realmPath, pathConfigurationCache);
    }//from  w  w  w . j  a v a  2  s.c  om

    if (pathConfigurationCache.size() > 0) {

        // For the current restrictions, it is enough to just check one of the existing configurations.
        RealmConfiguration cachedConfiguration = pathConfigurationCache.get(0);

        // Check that encryption keys aren't different
        if (!Arrays.equals(cachedConfiguration.getEncryptionKey(), newConfiguration.getEncryptionKey())) {
            throw new IllegalArgumentException(DIFFERENT_KEY_MESSAGE);
        }

        // Check schema versions are the same
        if (cachedConfiguration.getSchemaVersion() != newConfiguration.getSchemaVersion()) {
            throw new IllegalArgumentException(String.format(
                    "Configurations cannot have different schema versions "
                            + "if used to open the same file. %d vs. %d",
                    cachedConfiguration.getSchemaVersion(), newConfiguration.getSchemaVersion()));
        }

        // Check that schema is the same
        RealmProxyMediator cachedSchema = cachedConfiguration.getSchemaMediator();
        RealmProxyMediator schema = newConfiguration.getSchemaMediator();
        if (!cachedSchema.equals(schema)) {
            throw new IllegalArgumentException("Two configurations with different schemas are trying to open "
                    + "the same Realm file. Their schema must be the same: " + newConfiguration.getPath());
        }
    }

    // The new configuration doesn't violate existing configurations. Cache it.
    pathConfigurationCache.add(newConfiguration);
}