List of usage examples for java.util.concurrent CopyOnWriteArrayList CopyOnWriteArrayList
public CopyOnWriteArrayList()
From source file:com.iitb.cse.Utils.java
public static CopyOnWriteArrayList<DeviceInfo> activeClients() { // (Utils.getCurrentTimeStamp().getTime() - device.getLastHeartBeatTime().getTime())/1000 > 60 // int count = 0; ConcurrentHashMap<String, DeviceInfo> clients = Constants.currentSession.getConnectedClients(); Enumeration<String> macList = clients.keys(); ConcurrentHashMap<String, DeviceInfo> connectedClients = new ConcurrentHashMap<String, DeviceInfo>(); CopyOnWriteArrayList<DeviceInfo> activeClients = new CopyOnWriteArrayList<DeviceInfo>(); if (clients != null) { while (macList.hasMoreElements()) { String macAddr = macList.nextElement(); DeviceInfo device = clients.get(macAddr); if ((Utils.getCurrentTimeStamp().getTime() - device.getLastHeartBeatTime().getTime()) / 1000 <= Constants.heartBeatAlive) { activeClients.add(device); // count++; }//from w w w.ja va2s.c o m } } return activeClients; }
From source file:com.web.server.WarDeployer.java
/** * This method is the implementation of the war deployer which frequently scans the deploy * directory and if there is a change in war redeploys and configures the map *//* w w w . j a va2 s. c o m*/ public void run() { File file; ConcurrentHashMap filePrevMap = new ConcurrentHashMap(); ConcurrentHashMap fileCurrMap = new ConcurrentHashMap(); ; FileInfo filePrevLastModified; FileInfo fileCurrLastModified; String filePath; FileInfo fileinfoTmp; URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader(); URL[] urls = loader.getURLs(); warsDeployed = new CopyOnWriteArrayList(); //System.out.println("URLS="+urls[0]); WebClassLoader customClassLoader; while (true) { file = new File(scanDirectory); File[] files = file.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) continue; //Long lastModified=(Long) fileMap.get(files[i].getName()); if (files[i].getName().endsWith(".war")) { filePath = files[i].getAbsolutePath(); //logger.info("filePath"+filePath); filePath = filePath.substring(0, filePath.toLowerCase().lastIndexOf(".war")); File warDirectory = new File(filePath); fileinfoTmp = new FileInfo(); fileinfoTmp.setFile(files[i]); fileinfoTmp.setLastModified(files[i].lastModified()); if (!warDirectory.exists() || fileCurrMap.get(files[i].getName()) == null && filePrevMap.get(files[i].getName()) == null) { if (warDirectory.exists()) { deleteDir(warDirectory); } customClassLoader = new WebClassLoader(urls); synchronized (urlClassLoaderMap) { logger.info("WARDIRECTORY=" + warDirectory.getAbsolutePath()); urlClassLoaderMap.put(warDirectory.getAbsolutePath().replace("\\", "/"), customClassLoader); } extractWar(files[i], customClassLoader); //System.out.println("War Deployed Successfully in path: "+filePath); AddUrlToClassLoader(warDirectory, customClassLoader); numberOfWarDeployed++; logger.info(files[i] + " Deployed"); warsDeployed.add(files[i].getName()); filePrevMap.put(files[i].getName(), fileinfoTmp); } fileCurrMap.put(files[i].getName(), fileinfoTmp); } /*if(lastModified==null||lastModified!=files[i].lastModified()){ fileMap.put(files[i].getName(),files[i].lastModified()); }*/ } Set keyset = fileCurrMap.keySet(); Iterator ite = keyset.iterator(); String fileName; while (ite.hasNext()) { fileName = (String) ite.next(); //logger.info("fileName"+fileName); filePrevLastModified = (FileInfo) filePrevMap.get(fileName); fileCurrLastModified = (FileInfo) fileCurrMap.get(fileName); if (filePrevLastModified != null) //logger.info("lastmodified="+filePrevLastModified.getLastModified()); //System.out.println("prevmodified"+fileCurrLastModified.getLastModified()+""+filePrevLastModified.getLastModified()); if (fileCurrLastModified != null) { //System.out.println("prevmodified"+fileCurrLastModified.getLastModified()); } if (filePrevLastModified == null || filePrevLastModified.getLastModified() != fileCurrLastModified.getLastModified()) { filePath = fileCurrLastModified.getFile().getAbsolutePath(); //logger.info("filePath"+filePath); filePath = filePath.substring(0, filePath.toLowerCase().lastIndexOf(".war")); File warDirectory = new File(filePath); //logger.info("WARDIRECTORY="+warDirectory.getAbsolutePath()); if (warDirectory.exists()) { WebClassLoader webClassLoader = (WebClassLoader) urlClassLoaderMap .get(warDirectory.getAbsolutePath().replace("\\", "/")); synchronized (executorServiceMap) { try { new ExecutorServicesConstruct().removeExecutorServices(executorServiceMap, new File(warDirectory.getAbsolutePath().replace("\\", "/") + "/WEB-INF/" + "executorservices.xml"), webClassLoader); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } //System.out.println("executorServiceMap"+executorServiceMap); } synchronized (messagingClassMap) { try { new MessagingClassConstruct().removeMessagingClass(messagedigester, new File(warDirectory.getAbsolutePath().replace("\\", "/") + "/WEB-INF/" + "messagingclass.xml"), messagingClassMap); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("executorServiceMap" + executorServiceMap); } ClassLoaderUtil.cleanupJarFileFactory(ClassLoaderUtil.closeClassLoader(webClassLoader)); try { webClassLoader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } logger.info("ServletMapping" + servletMapping); logger.info("warDirectory=" + warDirectory.getAbsolutePath().replace("\\", "/")); urlClassLoaderMap.remove(warDirectory.getAbsolutePath().replace("\\", "/")); WebAppConfig webAppConfig = (WebAppConfig) servletMapping .remove(warDirectory.getAbsolutePath().replace("\\", "/")); System.gc(); deleteDir(warDirectory); warsDeployed.remove(fileName); removeServletFromSessionObject(webAppConfig, warDirectory.getAbsolutePath().replace("\\", "/")); numberOfWarDeployed--; } customClassLoader = new WebClassLoader(urls); logger.info(customClassLoader); urlClassLoaderMap.put(warDirectory.getAbsolutePath().replace("\\", "/"), customClassLoader); extractWar(fileCurrLastModified.getFile(), customClassLoader); //System.out.println("War Deployed Successfully in path: "+fileCurrLastModified.getFile().getAbsolutePath()); AddUrlToClassLoader(warDirectory, customClassLoader); numberOfWarDeployed++; warsDeployed.add(fileName); logger.info(filePath + ".war Deployed"); } } keyset = filePrevMap.keySet(); ite = keyset.iterator(); while (ite.hasNext()) { fileName = (String) ite.next(); filePrevLastModified = (FileInfo) filePrevMap.get(fileName); fileCurrLastModified = (FileInfo) fileCurrMap.get(fileName); if (fileCurrLastModified == null) { filePath = filePrevLastModified.getFile().getAbsolutePath(); filePath = filePath.substring(0, filePath.toLowerCase().lastIndexOf(".war")); logger.info("filePath" + filePath); File deleteDirectory = new File(filePath); logger.info("Delete Directory" + deleteDirectory.getAbsolutePath().replace("\\", "/")); WebClassLoader webClassLoader = (WebClassLoader) urlClassLoaderMap .get(deleteDirectory.getAbsolutePath().replace("\\", "/")); ; synchronized (executorServiceMap) { try { new ExecutorServicesConstruct().removeExecutorServices(executorServiceMap, new File(deleteDirectory.getAbsolutePath().replace("\\", "/") + "/WEB-INF/" + "executorservices.xml"), webClassLoader); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } //System.out.println("executorServiceMap"+executorServiceMap); } synchronized (messagingClassMap) { try { new MessagingClassConstruct().removeMessagingClass(messagedigester, new File(deleteDirectory.getAbsolutePath().replace("\\", "/") + "/WEB-INF/" + "messagingclass.xml"), messagingClassMap); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } //System.out.println("executorServiceMap"+executorServiceMap); } WebAppConfig webAppConfig = (WebAppConfig) servletMapping .remove(deleteDirectory.getAbsolutePath().replace("\\", "/")); ClassLoaderUtil.cleanupJarFileFactory(ClassLoaderUtil.closeClassLoader(webClassLoader)); urlClassLoaderMap.remove(deleteDirectory.getAbsolutePath().replace("\\", "/")); logger.info("ServletMapping" + servletMapping); logger.info("warDirectory=" + deleteDirectory.getAbsolutePath().replace("\\", "/")); try { logger.info(webClassLoader); logger.info("CLASSLOADER IS CLOSED"); webClassLoader.close(); } catch (Throwable e) { // TODO Auto-generated catch block e.printStackTrace(); } System.gc(); deleteDir(deleteDirectory); numberOfWarDeployed--; warsDeployed.remove(fileName); try { removeServletFromSessionObject(webAppConfig, deleteDirectory.getAbsolutePath().replace("\\", "/")); } catch (Exception ex) { ex.printStackTrace(); } logger.info(filePath + ".war Undeployed"); } } filePrevMap.keySet().removeAll(filePrevMap.keySet()); filePrevMap.putAll(fileCurrMap); fileCurrMap.keySet().removeAll(fileCurrMap.keySet()); //System.out.println("filePrevMap="+filePrevMap); //System.out.println("fileCurrMap="+fileCurrMap); try { Thread.sleep(3000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
From source file:iDynoOptimizer.MOEAFramework26.src.org.moeaframework.analysis.diagnostics.Controller.java
/** * Adds a new result to this controller. If the specified key already * exists, the accumulator is appended to the existing results. A * {@code MODEL_CHANGED} event is fired. * /* ww w . java 2s . c o m*/ * @param key the result key identifying the algorithm and problem * associated with these results * @param accumulator the accumulator storing the results */ public void add(ResultKey key, Accumulator accumulator) { synchronized (accumulators) { if (!accumulators.containsKey(key)) { accumulators.put(key, new CopyOnWriteArrayList<Accumulator>()); } accumulators.get(key).add(accumulator); lastAccumulator = accumulator; } fireModelChangedEvent(); }
From source file:lineage2.gameserver.model.EffectList.java
/** * Method addEffect.//from w ww. jav a 2 s . c om * @param effect Effect */ public void addEffect(Effect effect) { double hp = _actor.getCurrentHp(); double mp = _actor.getCurrentMp(); double cp = _actor.getCurrentCp(); boolean add = false; lock.lock(); try { if (_effects == null) { _effects = new CopyOnWriteArrayList<>(); } if (effect.getStackType().contains(EffectTemplate.NO_STACK)) { for (Effect e : _effects) { if (!e.isInUse()) { continue; } if (e.getStackType().contains(EffectTemplate.NO_STACK) && (e.getSkill().getId() == effect.getSkill().getId()) && (e.getEffectType() == effect.getEffectType())) { if (effect.getTimeLeft() > e.getTimeLeft()) { e.exit(); } else { return; } } } } else { for (Effect e : _effects) { if (!e.isInUse()) { continue; } if (!checkStackType(e.getTemplate(), effect.getTemplate())) { continue; } if ((e.getSkill().getId() == effect.getSkill().getId()) && (e.getEffectType() != effect.getEffectType())) { break; } if (e.getStackOrder() == -1) { return; } if (!e.maybeScheduleNext(effect)) { return; } } } checkSlotLimit(effect); add = _effects.add(effect); if (add) { effect.setInUse(true); } } finally { lock.unlock(); } if (!add) { return; } effect.start(); for (FuncTemplate ft : effect.getTemplate().getAttachedFuncs()) { if (ft._stat == Stats.MAX_HP) { _actor.setCurrentHp(hp, false); } else if (ft._stat == Stats.MAX_MP) { _actor.setCurrentMp(mp); } else if (ft._stat == Stats.MAX_CP) { _actor.setCurrentCp(cp); } } _actor.updateStats(); _actor.updateEffectIcons(); }
From source file:be.agiv.security.AGIVSecurity.java
private AGIVSecurity(String ipStsLocation, String rStsLocation, String rStsRealm, String username, String password, ExternalIPSTSClient externalIpStsClient, X509Certificate certificate, PrivateKey privateKey) {//w ww. j a v a 2 s .c o m this.ipStsLocation = ipStsLocation; this.rStsLocation = rStsLocation; this.rStsRealm = rStsRealm; this.username = username; this.password = password; this.certificate = certificate; this.privateKey = privateKey; this.externalIpStsClient = externalIpStsClient; this.secureConversationTokens = new ConcurrentHashMap<String, SecurityToken>(); this.rStsSecurityTokens = new ConcurrentHashMap<String, SecurityToken>(); this.stsListeners = new CopyOnWriteArrayList<STSListener>(); }
From source file:de.dfki.asr.compass.model.SceneNode.java
public <T extends SceneNodeComponent> List<T> getComponentsByType(final Class<T> clazz) { List<T> returnList = new CopyOnWriteArrayList<>(); for (SceneNodeComponent c : this.components) { if (clazz.isAssignableFrom(c.getClass())) { returnList.add((T) c);//from w w w. ja v a 2 s . com } } return returnList; }
From source file:events.TeamVsTeam.TeamVsTeam.java
public void start(String[] var) { Player player = getSelf();// www . j ava2 s . c om if (var.length != 2) { show("Error.", player); return; } Integer category; Integer autoContinue; try { category = Integer.valueOf(var[0]); autoContinue = Integer.valueOf(var[1]); } catch (Exception e) { show("Error.", player); return; } _category = category; _autoContinue = autoContinue; if (_category == -1) { _minLevel = 1; _maxLevel = 99; } else { _minLevel = getMinLevelForCategory(_category); _maxLevel = getMaxLevelForCategory(_category); } if (_endTask != null) { show("Try later.", player); return; } _status = 0; _isRegistrationActive = true; _time_to_start = Config.EVENT_TvTTime; players_list1 = new CopyOnWriteArrayList<>(); players_list2 = new CopyOnWriteArrayList<>(); live_list1 = new CopyOnWriteArrayList<>(); live_list2 = new CopyOnWriteArrayList<>(); playerRestoreCoord = new LinkedHashMap<>(); sayToAll("TvT: Start in " + String.valueOf(_time_to_start) + " min. for levels " + String.valueOf(_minLevel) + "-" + String.valueOf(_maxLevel) + ". Information in the community board (alt+b)."); executeTask("events.TeamVsTeam.TeamVsTeam", "question", new Object[0], 10000); executeTask("events.TeamVsTeam.TeamVsTeam", "announce", new Object[0], 60000); }
From source file:org.deeplearning4j.text.invertedindex.LuceneInvertedIndex.java
@Override public Pair<List<T>, String> documentWithLabel(int index) { List<T> ret = new CopyOnWriteArrayList<>(); String label = "NONE"; try {//from w ww . j a va 2s.c o m DirectoryReader reader = readerManager.acquire(); Document doc = reader.document(index); reader.close(); String[] values = doc.getValues(WORD_FIELD); label = doc.get(LABEL); if (label == null) label = "NONE"; for (String s : values) { T tok = vocabCache.wordFor(s); if (tok != null) ret.add(tok); } } catch (Exception e) { e.printStackTrace(); } return new Pair<>(ret, label); }
From source file:codeswarm.code_swarm.java
/** * Initialisation// www . j a v a 2 s . co m */ public void setup() { width = cfg.getIntProperty(CodeSwarmConfig.WIDTH_KEY, 640); if (width <= 0) { width = 640; } height = cfg.getIntProperty(CodeSwarmConfig.HEIGHT_KEY, 480); if (height <= 0) { height = 480; } maxBackgroundThreads = cfg.getIntProperty(CodeSwarmConfig.MAX_THREADS_KEY, 4); if (maxBackgroundThreads <= 0) { maxBackgroundThreads = 4; } backgroundExecutor = new ThreadPoolExecutor(1, maxBackgroundThreads, Long.MAX_VALUE, TimeUnit.NANOSECONDS, new ArrayBlockingQueue<Runnable>(4 * maxBackgroundThreads), new ThreadPoolExecutor.CallerRunsPolicy()); if (cfg.getBooleanProperty(CodeSwarmConfig.USE_OPEN_GL, false)) { size(width, height, OPENGL); } else { size(width, height); } showLegend = cfg.getBooleanProperty(CodeSwarmConfig.SHOW_LEGEND, false); showHistogram = cfg.getBooleanProperty(CodeSwarmConfig.SHOW_HISTORY, false); showDate = cfg.getBooleanProperty(CodeSwarmConfig.SHOW_DATE, false); showEdges = cfg.getBooleanProperty(CodeSwarmConfig.SHOW_EDGES, false); showDebug = cfg.getBooleanProperty(CodeSwarmConfig.SHOW_DEBUG, false); takeSnapshots = cfg.getBooleanProperty(CodeSwarmConfig.TAKE_SNAPSHOTS_KEY, false); drawNamesSharp = cfg.getBooleanProperty(CodeSwarmConfig.DRAW_NAMES_SHARP, true); drawNamesHalos = cfg.getBooleanProperty(CodeSwarmConfig.DRAW_NAMES_HALOS, false); drawFilesSharp = cfg.getBooleanProperty(CodeSwarmConfig.DRAW_FILES_SHARP, false); drawFilesFuzzy = cfg.getBooleanProperty(CodeSwarmConfig.DRAW_FILES_FUZZY, true); drawFilesJelly = cfg.getBooleanProperty(CodeSwarmConfig.DRAW_FILES_JELLY, false); background = cfg.getBackground().getRGB(); UPDATE_DELTA = cfg.getIntProperty(CodeSwarmConfig.MSEC_PER_FRAME_KEY, -1); if (UPDATE_DELTA == -1) { int framesperday = cfg.getIntProperty(CodeSwarmConfig.FRAMES_PER_DAY_KEY, 4); if (framesperday > 0) { UPDATE_DELTA = (86400000 / framesperday); } } if (UPDATE_DELTA <= 0) { // Default to 4 frames per day. UPDATE_DELTA = 21600000; } isInputSorted = cfg.getBooleanProperty(CodeSwarmConfig.IS_INPUT_SORTED_KEY, false); /** * This section loads config files and calls the setup method for all physics engines. */ physicsEngineConfigDir = cfg.getStringProperty(CodeSwarmConfig.PHYSICS_ENGINE_CONF_DIR, "physics_engine"); File f = new File(physicsEngineConfigDir); String[] configFiles = null; if (f.exists() && f.isDirectory()) { configFiles = f.list(); } for (int i = 0; configFiles != null && i < configFiles.length; i++) { if (configFiles[i].endsWith(".config")) { Properties p = new Properties(); String ConfigPath = physicsEngineConfigDir + System.getProperty("file.separator") + configFiles[i]; try { p.load(new FileInputStream(ConfigPath)); } catch (FileNotFoundException e) { e.printStackTrace(); System.exit(1); } catch (IOException e) { e.printStackTrace(); System.exit(1); } String ClassName = p.getProperty("name", "__DEFAULT__"); if (!ClassName.equals("__DEFAULT__")) { PhysicsEngine pe = getPhysicsEngine(ClassName); pe.setup(p); mPhysicsEngineChoices.add(pe); } else { logger.error("Skipping config file '" + ConfigPath + "'. Must specify class name via the 'name' parameter."); System.exit(1); } } } if (mPhysicsEngineChoices.size() == 0) { logger.error("No physics engine config files found in '" + physicsEngineConfigDir + "'."); System.exit(1); } // Physics engine configuration and instantiation physicsEngineSelection = cfg.getStringProperty(CodeSwarmConfig.PHYSICS_ENGINE_SELECTION, PHYSICS_ENGINE_LEGACY); for (PhysicsEngine p : mPhysicsEngineChoices) { if (physicsEngineSelection.equals(p.getClass().getName())) { mPhysicsEngine = p; } } if (mPhysicsEngine == null) { logger.error("No physics engine matches your choice of '" + physicsEngineSelection + "'. Check '" + physicsEngineConfigDir + "' for options."); System.exit(1); } smooth(); frameRate(FRAME_RATE); // init data structures nodes = new CopyOnWriteArrayList<FileNode>(); edges = new CopyOnWriteArrayList<Edge>(); people = new CopyOnWriteArrayList<PersonNode>(); history = new LinkedList<ColorBins>(); if (isInputSorted) { //If the input is sorted, we only need to store the next few events eventsQueue = new ArrayBlockingQueue<FileEvent>(5000); } else { //Otherwise we need to store them all at once in a data structure that will sort them eventsQueue = new PriorityBlockingQueue<FileEvent>(); } // Init color map initColors(); loadRepEvents(cfg.getStringProperty(CodeSwarmConfig.INPUT_FILE_KEY)); // event formatted (this is the standard) synchronized (this) { while (!finishedLoading && eventsQueue.isEmpty()) { try { wait(); } catch (InterruptedException e) { logger.error("The ready-check thread was interrupted", e); } } } prevDate = eventsQueue.peek().getDate(); SCREENSHOT_FILE = cfg.getStringProperty(CodeSwarmConfig.SNAPSHOT_LOCATION_KEY); maxFramesSaved = (int) Math.pow(10, SCREENSHOT_FILE.replaceAll("[^#]", "").length()); // Create fonts String fontName = cfg.getStringProperty(CodeSwarmConfig.FONT_KEY, "SansSerif"); String fontNameBold = cfg.getStringProperty(CodeSwarmConfig.FONT_KEY_BOLD, "SansSerif"); Integer fontSize = cfg.getIntProperty(CodeSwarmConfig.FONT_SIZE, 10); Integer fontSizeBold = cfg.getIntProperty(CodeSwarmConfig.FONT_SIZE_BOLD, 14); font = createFont(fontName, fontSize); boldFont = createFont(fontNameBold, fontSizeBold); textFont(font); // Create the file particle image sprite = loadImage(cfg.getStringProperty(CodeSwarmConfig.SPRITE_FILE_KEY, "particle.png")); // Add translucency (using itself in this case) sprite.mask(sprite); }
From source file:uk.ac.brighton.ci360.bigarrow.PlacesAPISearch.java
public void getPhotos(Photo[] photoRefsArr) { executorService = Executors.newFixedThreadPool(5); photoRefs = new ArrayList<Photo>(Arrays.asList(photoRefsArr)); photoResults = new CopyOnWriteArrayList<Bitmap>(); for (Photo p : photoRefs) { executorService.execute(new PhotoTask(p.photo_reference)); }/*w ww. j a v a 2s.c om*/ }