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(E[] toCopyIn) 

Source Link

Document

Creates a list holding a copy of the given array.

Usage

From source file:com.github.dozermapper.core.propertydescriptor.PropertyDescriptorFactory.java

public DozerPropertyDescriptor getPropertyDescriptor(Class<?> clazz, String theGetMethod, String theSetMethod,
        String mapGetMethod, String mapSetMethod, boolean isAccessible, boolean isIndexed, int index,
        String name, String key, boolean isSelfReferencing, String oppositeFieldName,
        HintContainer srcDeepIndexHintContainer, HintContainer destDeepIndexHintContainer, String beanFactory,
        BeanContainer beanContainer, DestBeanCreator destBeanCreator) {
    DozerPropertyDescriptor desc = null;

    // Raw Map types or custom map-get-method/set specified
    boolean isMapProperty = MappingUtils.isSupportedMap(clazz);
    if (name.equals(DozerConstants.SELF_KEYWORD)
            && (mapSetMethod != null || mapGetMethod != null || isMapProperty)) {

        // If no mapSetMethod is defined, default to "put"
        String setMethod = StringUtils.isBlank(mapSetMethod) ? "put" : mapSetMethod;

        // If no mapGetMethod is defined, default to "get".
        String getMethod = StringUtils.isBlank(mapGetMethod) ? "get" : mapGetMethod;

        desc = new MapPropertyDescriptor(clazz, name, isIndexed, index, setMethod, getMethod,
                key != null ? key : oppositeFieldName, srcDeepIndexHintContainer, destDeepIndexHintContainer,
                beanContainer, destBeanCreator);

        // Copy by reference(Not mapped backed properties which also use 'this'
        // identifier for a different purpose)
    } else if (isSelfReferencing) {
        desc = new SelfPropertyDescriptor(clazz);

        // Access field directly and bypass getter/setters
    } else if (isAccessible) {
        desc = new FieldPropertyDescriptor(clazz, name, isIndexed, index, srcDeepIndexHintContainer,
                destDeepIndexHintContainer, destBeanCreator);

        // Custom get-method/set specified
    } else if (theSetMethod != null || theGetMethod != null) {
        desc = new CustomGetSetPropertyDescriptor(clazz, name, isIndexed, index, theSetMethod, theGetMethod,
                srcDeepIndexHintContainer, destDeepIndexHintContainer, beanContainer, destBeanCreator);

        // If this object is an XML Bean - then use the XmlBeanPropertyDescriptor
    } else if (beanFactory != null && beanFactory.equals(DozerConstants.XML_BEAN_FACTORY)) {
        desc = new XmlBeanPropertyDescriptor(clazz, name, isIndexed, index, srcDeepIndexHintContainer,
                destDeepIndexHintContainer, beanContainer, destBeanCreator);
    }/*from  w w  w. jav a2  s  .co m*/

    if (desc != null) {
        return desc;
    }

    for (PropertyDescriptorCreationStrategy propertyDescriptorBuilder : new CopyOnWriteArrayList<>(
            pluggedDescriptorCreationStrategies)) {
        if (propertyDescriptorBuilder.isApplicable(clazz, name)) {
            desc = propertyDescriptorBuilder.buildFor(clazz, name, isIndexed, index, srcDeepIndexHintContainer,
                    destDeepIndexHintContainer);
            if (desc != null) {
                break;
            }
        }
    }

    if (desc == null) {
        // Everything else. It must be a normal bean with normal custom get/set methods
        desc = new JavaBeanPropertyDescriptor(clazz, name, isIndexed, index, srcDeepIndexHintContainer,
                destDeepIndexHintContainer, beanContainer, destBeanCreator);
    }

    return desc;
}

From source file:com.auditbucket.engine.service.MediationFacade.java

public Integer createHeaders(final Company company, final Fortress fortress,
        final List<MetaInputBean> inputBeans) throws DatagioException {
    fortress.setCompany(company);/*from  w w w  .  jav a 2  s . c o  m*/
    Long id = DateTime.now().getMillis();
    StopWatch watch = new StopWatch();
    watch.start();
    logger.info("Starting Batch [{}] - size [{}]", id, inputBeans.size());
    boolean newMode = true;
    if (newMode) {

        // Tune to balance against concurrency and batch transaction insert efficiency.
        List<List<MetaInputBean>> splitList = Lists.partition(inputBeans, 20);

        for (List<MetaInputBean> metaInputBeans : splitList) {

            class DLCommand implements Command {
                Iterable<MetaInputBean> headers = null;

                DLCommand(List<MetaInputBean> processList) {
                    this.headers = new CopyOnWriteArrayList<>(processList);
                }

                @Override
                public Command execute() throws DatagioException {
                    //fortressService.registerFortress(company, new FortressInputBean(headers.iterator().next().getFortress()), true);
                    Iterable<TrackResultBean> resultBeans = trackService.createHeaders(headers, company,
                            fortress);
                    processLogs(company, resultBeans);
                    return this;
                }
            }
            DeadlockRetry.execute(new DLCommand(metaInputBeans), "creating headers", 20);
        }

    } else {
        logger.info("Processing in slow Transaction mode");
        for (MetaInputBean inputBean : inputBeans) {
            createHeader(company, fortress, inputBean);
        }
    }
    watch.stop();
    logger.info("Completed Batch [{}] - secs= {}, RPS={}", id, f.format(watch.getTotalTimeSeconds()),
            f.format(inputBeans.size() / watch.getTotalTimeSeconds()));
    return inputBeans.size();
}

From source file:dk.dma.msiproxy.common.provider.AbstractProviderService.java

/**
 * Updates the full list of active MSI messages
 * @param messages the new full list of active MSI messages
 *///from   w  w w  . j  av  a 2 s  .  com
protected synchronized void setActiveMessages(List<Message> messages) {
    this.messages = new CopyOnWriteArrayList<>(messages);
    this.fetchTime = System.currentTimeMillis();

    // Enforce the provider attribute of the messages
    this.messages.forEach(msg -> msg.setProvider(getProviderId()));

    getCache().clear();
}

From source file:com.haulmont.addon.zookeeper.discovery.ZkServerSelector.java

protected void initialDiscovery() {
    List<String> list = new ArrayList<>();
    try {//from w  ww  .  j a v  a2s  .  c  om
        if (curator.checkExists().forPath(ZkProperties.ROOT_PATH) != null) {
            for (String node : curator.getChildren().forPath(ZkProperties.ROOT_PATH)) {
                String nodePath = ZKPaths.makePath(ZkProperties.ROOT_PATH, node);
                byte[] bytes = curator.getData().forPath(nodePath);
                if (bytes != null) {
                    String url = new String(bytes, StandardCharsets.UTF_8);
                    if (!list.contains(url))
                        list.add(url);
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException("Error reading servers list", e);
    }
    log.info("Discovered servers: {}", list);
    urls = new CopyOnWriteArrayList<>(list.stream().map(this::serverIdToUrl).collect(Collectors.toList()));
}

From source file:sx.blah.discord.modules.ModuleLoader.java

/**
 * Attempts to {@link #loadModule(IModule) load} all {@link #getLoadedModules() loaded modules}.
 *///from w  w w .  j  a va2 s  .  co m
public void loadModules() {
    List<IModule> toLoad = new CopyOnWriteArrayList<>(loadedModules);
    while (toLoad.size() > 0) {
        for (IModule module : toLoad) {
            if (loadModule(module))
                toLoad.remove(module);
        }
    }
}

From source file:org.apache.axis2.jaxws.handler.HandlerChainProcessor.java

public HandlerChainProcessor(List<Handler> chain, Protocol proto) {
    if (chain != null) {
        synchronized (chain) {
            if (chain.size() == 0) {
                // Use empty chain to avoid excessive garbage collection
                this.handlers = EMPTY_CHAIN;
            } else {
                this.handlers = new CopyOnWriteArrayList<Handler>(chain);
            }/*  www. jav  a2 s  . c  o  m*/
        }
    } else {
        handlers = EMPTY_CHAIN;
    }
    this.proto = proto;
}

From source file:com.adobe.acs.commons.oak.impl.EnsureOakIndex.java

@Override
public void setIgnoreProperties(String[] ignoreProperties) {
    this.ignoreProperties = new CopyOnWriteArrayList<String>(ignoreProperties);
}

From source file:org.apache.hadoop.yarn.server.nodemanager.DirectoryCollection.java

/**
 * Create collection for the directories specified. Users must specify the
 * maximum percentage of disk utilization allowed and the minimum amount of
 * free space that must be available for the dir to be used. If either check
 * fails the dir is removed from the good dirs list.
 * //w  w w.j av  a 2 s . c  o m
 * @param dirs
 *          directories to be monitored
 * @param utilizationPercentageCutOffHigh
 *          percentage of disk that can be used before the dir is taken out of
 *          the good dirs list
 * @param utilizationPercentageCutOffLow
 *          percentage of disk that can be used when the dir is moved from
 *          the bad dirs list to the good dirs list
 * @param utilizationSpaceCutOff
 *          minimum space, in MB, that must be available on the disk for the
 *          dir to be marked as good
 * 
 */
public DirectoryCollection(String[] dirs, float utilizationPercentageCutOffHigh,
        float utilizationPercentageCutOffLow, long utilizationSpaceCutOff) {
    localDirs = new CopyOnWriteArrayList<>(dirs);
    errorDirs = new CopyOnWriteArrayList<>();
    fullDirs = new CopyOnWriteArrayList<>();

    ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    this.readLock = lock.readLock();
    this.writeLock = lock.writeLock();

    diskUtilizationPercentageCutoffHigh = Math.max(0.0F, Math.min(100.0F, utilizationPercentageCutOffHigh));
    diskUtilizationPercentageCutoffLow = Math.max(0.0F,
            Math.min(diskUtilizationPercentageCutoffHigh, utilizationPercentageCutOffLow));
    diskUtilizationSpaceCutoff = utilizationSpaceCutOff < 0 ? 0 : utilizationSpaceCutOff;

    dirsChangeListeners = Collections.newSetFromMap(new ConcurrentHashMap<DirsChangeListener, Boolean>());
}

From source file:org.opencds.service.evaluate.OpenCDSMain.java

/**
 * Note that there is currently a logical constraint that OpenCDS requires all of the list of KMs 
 *       (when there is more than one) to use the same inference engine adapter and vmr version.
 * /*from  www.jav  a  2s.  c  o m*/
 * It is also a constraint that iterative and non-iterative KMs cannot be used 
 *       in the same request.
 *
 * big picture pseudo code for this method:
 * 
 *       unmarshal the input and
 *       save the data as JaxB structures
 *       for each requestedKmId { 
 *          load factLists and ConceptLists from data
 *          pass the following to the DecisionEngine specified for the KM:
  *            requestedKmId,
  *             externalFactModelSSId,
  *           inputPayloadString,
  *           evalTime,
  *           clientLanguage,
  *           clientTimeZoneOffset
  *        }
  *        stack individual results as Base64 data for each requested KmId
  *     } 
 *       return dSSRequestList containing results from all requestedKM
 * 
 * This means that we are considering the OMG-HL7-CDSS concept of KnowledgeModule equivalent to
 * the Drools concept of KnowledgeBase.
 * 
 * It also means that we are only allowing one SSID for a set of one or more KMID.
 */

public static List<KMEvaluationRequest> decodeInput(EvaluationRequest evaluationRequest,
        java.util.Date evalTime, DSSRequestDataItem dssRequestDataItem, TimingData timingData)
        throws InvalidDriDataFormatExceptionFault, RequiredDataNotProvidedExceptionFault,
        EvaluationExceptionFault, InvalidTimeZoneOffsetExceptionFault, UnrecognizedScopedEntityExceptionFault,
        UnrecognizedLanguageExceptionFault, UnsupportedLanguageExceptionFault, DSSRuntimeExceptionFault {
    log.debug("II: " + dssRequestDataItem.getInteractionId() + " starting OpenCDSMain.decodeInput");
    timingData.setStartMessageRequestTime(new AtomicLong(System.nanoTime()));
    String inputPayloadString = "";

    /*
     * get data from dss wrapper
     * 
     */
    List<DataRequirementItemData> listDRIData = new CopyOnWriteArrayList<DataRequirementItemData>(
            evaluationRequest.getDataRequirementItemData());

    //FIXME flesh out and implement the following
    validateDRIDataFormat(listDRIData);
    validateScopedEntityIDRecognized(listDRIData);

    /**
     *  Note that OpenCDS only supports one payload at a time, 
     *  even though the DSS standard supports more than one.
     */

    //TODO change this code to stack input payloads, possibly including mixing vMR with CCD and/or HL7v2.x data...
    if (listDRIData.size() != 1) {
        log.warn("OpenCDSMain.getInputPayloadString did not have exactly 1 payload.  It had "
                + listDRIData.size() + " payloads, and only the first one can be used.");
    }

    dssRequestDataItem.setTimingData(timingData);
    dssRequestDataItem.getTimingData().setStartMessageRequestTime(new AtomicLong(System.nanoTime()));
    //dssRequestDataItem.setInteractionId(ii.getInteractionId());
    dssRequestDataItem.setEvalTime(evalTime);
    dssRequestDataItem.setClientLanguage(evaluationRequest.getClientLanguage());
    dssRequestDataItem.setClientTimeZoneOffset(evaluationRequest.getClientTimeZoneOffset());
    dssRequestDataItem.setInputItemName(listDRIData.get(0).getDriId().getItemId());
    dssRequestDataItem.setInputContainingEntityId(
            DSSUtility.makeEIString(listDRIData.get(0).getDriId().getContainingEntityId()));
    dssRequestDataItem.setExternalFactModelSSId(
            DSSUtility.makeEIString(listDRIData.get(0).getData().getInformationModelSSId()));

    try {
        inputPayloadString = getInputPayloadString(listDRIData.get(0));
        log.trace(inputPayloadString);

        dssRequestDataItem.setInputPayloadString(inputPayloadString);

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        throw new DSSRuntimeExceptionFault(
                "OpenCDSMain.getInputPayloadString had UnsupportedEncoding Exception: " + e.getMessage());
    }

    timingData.setStartUnmarshalTime(new AtomicLong(System.nanoTime()));

    String externalFactModelSSId = DSSUtility.makeEIString(
            evaluationRequest.getDataRequirementItemData().get(0).getData().getInformationModelSSId());

    /**
     * IPayloadInboundProcessor is returned from cache, if available, otherwise it is instantiated and cached and then returned
     * 
     */

    IPayloadInboundProcessor payloadInboundProcessor = PayloadInboundProcessorFactory
            .getPayloadInboundProcessor(externalFactModelSSId);

    dssRequestDataItem.setCdsInput(((IPayloadInboundProcessor) payloadInboundProcessor)
            .mappingInbound(inputPayloadString, evalTime, timingData));

    log.debug("II: " + dssRequestDataItem.getInteractionId() + " unmarshalling completed");

    /**
     * get List of Rules to run from dss wrapper
     * 
     */
    timingData.setStartInferenceEngineLoopTime(new AtomicLong(System.nanoTime()));

    List<KMEvaluationRequest> listKMERequest = new CopyOnWriteArrayList<KMEvaluationRequest>(
            evaluationRequest.getKmEvaluationRequest());

    for (KMEvaluationRequest oneKMEvaluationRequest : listKMERequest) {
        List<ItemIdentifier> listFactItemTypes = new CopyOnWriteArrayList<ItemIdentifier>();
        for (DataRequirementItemData oneDataRequirementItemData : listDRIData) {
            listFactItemTypes.add(oneDataRequirementItemData.getDriId());
        }
        validateRequiredDataProvided(listFactItemTypes, oneKMEvaluationRequest);
    }

    log.debug("II: " + dssRequestDataItem.getInteractionId() + " input data validated");

    return listKMERequest;
}

From source file:de.jackwhite20.japs.server.JaPSServer.java

public void subscribeChannel(String channel, Connection connection) {

    if (channelSessions.containsKey(channel)) {
        channelSessions.get(channel).add(connection);
    } else {/*from  w w  w .j a v a  2 s .c  om*/
        channelSessions.put(channel, new CopyOnWriteArrayList<>(Collections.singletonList(connection)));
    }

    LOGGER.log(Level.FINE, "[{0}] Channel subscribed: {1}",
            new Object[] { connection.remoteAddress().toString(), channel });
}