Java Code Examples for java.util.concurrent.ConcurrentHashMap.put()

The following are Jave code examples for showing how to use put() of the java.util.concurrent.ConcurrentHashMap class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: tensorflow   File: WordVocabulary.java   View Source Code Vote up 7 votes
private ConcurrentHashMap<String, Integer> buildVocabulary(InputStream input) throws IOException {

		ConcurrentHashMap<String, Integer> vocabulary = new ConcurrentHashMap<>();

		try (BufferedReader buffer = new BufferedReader(new InputStreamReader(input))) {
			String l = buffer.readLine();
			while (l != null ) {
				String p[] = l.split(",");
				if (p[1].length() > 1) {
					vocabulary.put(p[0], Integer.valueOf(p[1]));
				}
				l = buffer.readLine();
			}
		}
		return vocabulary;
	}
 
Example 2
Project: cljbuck   File: Main.java   View Source Code Vote up 7 votes
/**
 * Composes the list of commands and initialises them with the build graph.
 *
 *
 * @param logger
 * @param buildGraph
 * @param classPath
 * @param workspace
 * @return
 */
private ConcurrentHashMap<String, Command> commandList(final Tracer logger, final BuildGraph buildGraph, final ClassPath classPath, final Workspace workspace) {
    final ConcurrentHashMap<String, Command> commands = new ConcurrentHashMap<>();
    final ArrayList<Command> list = new ArrayList<>();

    final BuildCommand buildCommand = new BuildCommand(logger, buildGraph, classPath, workspace.getOutputDir());

    list.add(buildCommand);
    list.add(new PrintDepsCommand(logger, buildGraph));
    list.add(new ReplCommand(logger, buildGraph, classPath, buildCommand));
    list.add(new RunCommand(logger, buildGraph, classPath, buildCommand));
    list.add(new PrintTargetsCommand(logger, buildGraph));

    for (final Command c : list) {
        commands.put(c.getTarget(), c);
    }

    return commands;
}
 
Example 3
Project: usb-with-serial-port   File: SerialPortFinder.java   View Source Code Vote up 7 votes
private ConcurrentHashMap<String,String> findAllDevices(){
	ConcurrentHashMap<String,String> devices = new ConcurrentHashMap<>();
	// Parse each driver
	Iterator<Driver> itdriv;
	try {
		itdriv = getDrivers().iterator();
		while(itdriv.hasNext()) {
			Driver driver = itdriv.next();
			for (File file : driver.getDevices()) {
				String deviceName = file.getName();
				String devicePath = file.getAbsolutePath();
				deviceName = String.format("%s (%s)", deviceName, driver.getName());
				Log.d("SerialPortFinder", "findAllDevices device name : " + deviceName + " , device path : " + devicePath);
				devices.put(deviceName, devicePath);
			}
		}
	} catch (IOException e) {
		e.printStackTrace();
	}
	return devices;
}
 
Example 4
Project: monarch   File: RegionVersionVector.java   View Source Code Vote up 7 votes
/**
 * Retrieve a vector that can be sent to another member. This clones all of the version
 * information to protect against concurrent modification during serialization
 */
public RegionVersionVector<T> getCloneForTransmission() {
  Map<T, RegionVersionHolder<T>> liveHolders;
  liveHolders = new HashMap<T, RegionVersionHolder<T>>(this.memberToVersion);
  ConcurrentHashMap<T, RegionVersionHolder<T>> clonedHolders =
      new ConcurrentHashMap<T, RegionVersionHolder<T>>(liveHolders.size(), LOAD_FACTOR,
          CONCURRENCY_LEVEL);
  for (Map.Entry<T, RegionVersionHolder<T>> entry : liveHolders.entrySet()) {
    clonedHolders.put(entry.getKey(), entry.getValue().clone());
  }
  ConcurrentHashMap<T, Long> gcVersions = new ConcurrentHashMap<T, Long>(
      this.memberToGCVersion.size(), LOAD_FACTOR, CONCURRENCY_LEVEL);
  gcVersions.putAll(this.memberToGCVersion);
  RegionVersionHolder<T> clonedLocalHolder;
  clonedLocalHolder = this.localExceptions.clone();
  // Make sure the holder that we send to the peer does
  // have an accurate RegionVersionHolder for our local version
  return createCopy(this.myId, clonedHolders, this.localVersion.get(), gcVersions,
      this.localGCVersion.get(), false, clonedLocalHolder);
}
 
Example 5
Project: rocketmq-rocketmq-all-4.1.0-incubating   File: RouteInfoManagerTest.java   View Source Code Vote up 7 votes
@Test
public void testRegisterBroker() {
    TopicConfigSerializeWrapper topicConfigSerializeWrapper = new TopicConfigSerializeWrapper();
    ConcurrentHashMap<String, TopicConfig> topicConfigConcurrentHashMap = new ConcurrentHashMap<>();
    TopicConfig topicConfig = new TopicConfig();
    topicConfig.setWriteQueueNums(8);
    topicConfig.setTopicName("unit-test");
    topicConfig.setPerm(6);
    topicConfig.setReadQueueNums(8);
    topicConfig.setOrder(false);
    topicConfigConcurrentHashMap.put("unit-test", topicConfig);
    topicConfigSerializeWrapper.setTopicConfigTable(topicConfigConcurrentHashMap);
    Channel channel = mock(Channel.class);
    RegisterBrokerResult registerBrokerResult = routeInfoManager.registerBroker("default-cluster", "127.0.0.1:10911", "default-broker", 1234, "127.0.0.1:1001",
        topicConfigSerializeWrapper, new ArrayList<String>(), channel);
    assertThat(registerBrokerResult).isNotNull();
}
 
Example 6
Project: PraFramework   File: EventManager.java   View Source Code Vote up 7 votes
/**
 * Registers the non-static listener methods of a given object
 * @param listener the object
 */
public void addListener(Object listener) {

    try {
        for (Method method : listener.getClass().getDeclaredMethods()) {
            if (method.isAnnotationPresent(EventHandler.class)) {
                if (method.getParameterCount() == 1 && Event.class.isAssignableFrom(method.getParameters()[0].getType())) {
                    EventHandler annotation = method.getAnnotation(EventHandler.class);
                    ConcurrentHashMap<EventPrio, ArrayList<Listener>> listeners = eventListener.getOrDefault(method.getParameters()[0].getType().getName(), new ConcurrentHashMap<>());
                    ArrayList<Listener> methods = listeners.getOrDefault(annotation.prio(), new ArrayList<>());
                    method.setAccessible(true);
                    methods.add(new Listener(listener, method));
                    listeners.put(annotation.prio(), methods);
                    eventListener.put((method.getParameters()[0].getType().getName()), listeners);
                }
            }
        }
    } catch (Exception e) {
        ExceptionHandler.addException(e);
    }
}
 
Example 7
Project: openjdk-jdk10   File: DistinctEntrySetElements.java   View Source Code Vote up 7 votes
public static void main(String[] args) throws Exception {
    final ConcurrentHashMap<String, String> concurrentHashMap =
        new ConcurrentHashMap<>();

    concurrentHashMap.put("One", "Un");
    concurrentHashMap.put("Two", "Deux");
    concurrentHashMap.put("Three", "Trois");

    Set<Map.Entry<String, String>> entrySet = concurrentHashMap.entrySet();
    HashSet<Map.Entry<String, String>> hashSet = new HashSet<>(entrySet);

    if (false == hashSet.equals(entrySet)) {
        throw new RuntimeException("Test FAILED: Sets are not equal.");
    }
    if (hashSet.hashCode() != entrySet.hashCode()) {
        throw new RuntimeException("Test FAILED: Set's hashcodes are not equal.");
    }
}
 
Example 8
Project: dooo   File: WashMap.java   View Source Code Vote up 6 votes
public static void main(String[] args) {
    ArrayList<String> list = new ArrayList<>(Arrays.asList("I", "love", "you", "too"));

    list.removeIf(new Predicate<String>() {
        @Override
        public boolean test(String s) {
            if (s.length() < 2) {

                return true;
            }
            return false;
        }
    });
    list.removeIf(l -> l.length() < 4);
    System.out.println(JSON.toJSONString(list));
    Date date = new Date();

    ConcurrentHashMap concurrentHashMap = new ConcurrentHashMap<>();
    concurrentHashMap.put("ds", 1);
    concurrentHashMap.computeIfAbsent("fdfd", k -> k.toString());
    System.out.println(JSON.toJSONString(concurrentHashMap));
    HashMap hashMap = new HashMap<>();
    hashMap.put("fd1", 1);
    hashMap.put("fd2", 1);
    hashMap.put("fd3", 1);
    hashMap.put("fd4", "fd");
    hashMap.put("fd5", 1);
    hashMap.entrySet().stream().forEach(hash -> {
        System.out.println(hash.toString());
    });
}
 
Example 9
Project: doctorkafka   File: ReplicaStatsManager.java   View Source Code Vote up 6 votes
public static void updateReplicaReassignmentTimestamp(String brokerZkUrl,
                                                       ReplicaStat replicaStat) {
  if (!replicaReassignmentTimestamps.containsKey(brokerZkUrl)) {
    replicaReassignmentTimestamps.put(brokerZkUrl, new ConcurrentHashMap<>());
  }
  ConcurrentHashMap<TopicPartition, Long> replicaTimestamps =
      replicaReassignmentTimestamps.get(brokerZkUrl);
  TopicPartition topicPartition = new TopicPartition(
      replicaStat.getTopic(), replicaStat.getPartition());

  if (!replicaTimestamps.containsKey(topicPartition) ||
      replicaTimestamps.get(topicPartition) < replicaStat.getTimestamp()) {
    replicaTimestamps.put(topicPartition, replicaStat.getTimestamp());
  }
}
 
Example 10
Project: openjdk-jdk10   File: ConcurrentHashMapTest.java   View Source Code Vote up 6 votes
/**
 * put(null,x) throws NPE
 */
public void testPut1_NullPointerException() {
    ConcurrentHashMap c = new ConcurrentHashMap(5);
    try {
        c.put(null, "whatever");
        shouldThrow();
    } catch (NullPointerException success) {}
}
 
Example 11
Project: openjdk-jdk10   File: ConcurrentHashMapTest.java   View Source Code Vote up 6 votes
/**
 * remove(null) throws NPE
 */
public void testRemove1_NullPointerException() {
    ConcurrentHashMap c = new ConcurrentHashMap(5);
    c.put("sadsdf", "asdads");
    try {
        c.remove(null);
        shouldThrow();
    } catch (NullPointerException success) {}
}
 
Example 12
Project: lams   File: JdbcTypeJavaClassMappings.java   View Source Code Vote up 6 votes
private static ConcurrentHashMap<Class, Integer> buildJdbcJavaClassMappings() {
	ConcurrentHashMap<Class, Integer> jdbcJavaClassMappings = new ConcurrentHashMap<Class, Integer>();

	// these mappings are the ones outlined specifically in the spec
	jdbcJavaClassMappings.put( String.class, Types.VARCHAR );
	jdbcJavaClassMappings.put( BigDecimal.class, Types.NUMERIC );
	jdbcJavaClassMappings.put( Boolean.class, Types.BIT );
	jdbcJavaClassMappings.put( Integer.class, Types.INTEGER );
	jdbcJavaClassMappings.put( Long.class, Types.BIGINT );
	jdbcJavaClassMappings.put( Float.class, Types.REAL );
	jdbcJavaClassMappings.put( Double.class, Types.DOUBLE );
	jdbcJavaClassMappings.put( byte[].class, Types.LONGVARBINARY );
	jdbcJavaClassMappings.put( java.sql.Date.class, Types.DATE );
	jdbcJavaClassMappings.put( Time.class, Types.TIME );
	jdbcJavaClassMappings.put( Timestamp.class, Types.TIMESTAMP );
	jdbcJavaClassMappings.put( Blob.class, Types.BLOB );
	jdbcJavaClassMappings.put( Clob.class, Types.CLOB );
	jdbcJavaClassMappings.put( Array.class, Types.ARRAY );
	jdbcJavaClassMappings.put( Struct.class, Types.STRUCT );
	jdbcJavaClassMappings.put( Ref.class, Types.REF );
	jdbcJavaClassMappings.put( Class.class, Types.JAVA_OBJECT );

	// additional "common sense" registrations
	jdbcJavaClassMappings.put( Character.class, Types.CHAR );
	jdbcJavaClassMappings.put( char[].class, Types.VARCHAR );
	jdbcJavaClassMappings.put( Character[].class, Types.VARCHAR );
	jdbcJavaClassMappings.put( Byte[].class, Types.LONGVARBINARY );
	jdbcJavaClassMappings.put( java.util.Date.class, Types.TIMESTAMP );
	jdbcJavaClassMappings.put( Calendar.class, Types.TIMESTAMP );

	return jdbcJavaClassMappings;
}
 
Example 13
Project: Long-Map-Benchmarks   File: MapTests.java   View Source Code Vote up 6 votes
@Benchmark
public ConcurrentHashMap concurrentHashMapCopy(Context context) { //Populates a map, then copies it
	ConcurrentHashMap<Long, Object> map = new ConcurrentHashMap<>();
	
	//Populate the map the first time
	for (int i = 0; i < context.testValues.length; i++)
		map.put(context.testKeys[i], context.testValues[i]);
	
	//Copy!
	ConcurrentHashMap<Long, Object> copy = new ConcurrentHashMap<>(map);
	return copy;
}
 
Example 14
Project: dataset-lib   File: AppServer.java   View Source Code Vote up 5 votes
@Hidden
public void recieve(int port,int paramBufferSize,int maxFileSize) {
    ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
    serverSocketChannel.socket().bind(new InetSocketAddress(port));
    ByteBuffer parameters = ByteBuffer.allocate(paramBufferSize);
    ByteBuffer content = ByteBuffer.allocate(maxFileSize);
    CharBuffer buffer = CharBuffer.allocate(paramBufferSize);
    List < ScheduledFuture > futures = new ArrayList < ScheduledFuture > ();
    ExecutorService executorService = Executors.newFixedThreadPool(maxAgents);
    int currentConnections;
    Method[] methods=servlet.class.getDeclaredMethods();
    List<String> methodNames=new ArrayList<String>();
    ConcurrentHashMap<String,Method> hashMap=new ConcurrentHashMap<String,Method>();
    SocketChannel[] sections;
    for(Method method:methods){
        Annotation[] annotations=method.getAnnotations();
        if(Arrays.asList(annotations).contains(Hidden.class)){
            continue;
        }
        else{
        hashMap.put(method.getName(),method);
        methodNames.add(method.getName());
        }
    }
    Runnable serverThread = () -> {
       /* socketChannel.read(parameters);
        if (params[0].equals("put")) {
            socketChannel.read(content);
            
        }
        buffer = buff.asCharBuffer();
        String str = buffer.toString();
        String[] params = str.split(":");
        if (params[0].equals("put")) {       
            java.nio.file.Path p = Paths.get(tempPath + params[2]);
            Files.write(p, content.array());
            this.put(params);
            Files.delete(p);
        } else if (params[0].equals("get")) {
            ByteBuffer b = this.get(params);
            socketChannel.write(b);
        } else if (params[0].equals("remove")) {
            this.remove(params);
        }
        futures.remove(i);*/
        
    };
    while (acceptingConnections) {
        socketChannel[0] = serverSocketChannel.accept();
        if (socketChannel != null) {
            ScheduledFuture future = executorService.submit(serverThread);
            i = futures.size();
            futures.add(future);
        }
    }
}
 
Example 15
Project: information-retrieval   File: SearchEngine.java   View Source Code Vote up 5 votes
/**
 * Searches for a token within the index
 * @param token the token
 * @return a mapping between the found token and document IDs
 */
public ConcurrentHashMap<String, ConcurrentHashMap<Integer, Double>> search(String token) {
    ConcurrentHashMap<String, ConcurrentHashMap<Integer, Double>> mapping = new ConcurrentHashMap<>();

    int level = checkSplitLevel(token);

    if (tmap_cache.entrySet().stream().sequential().noneMatch(entry -> entry.getKey().equals(token.substring(0, level)))) {
        //tmap not loaded - we need to load the correspondent map to search for matching docIDs
        String l_idx = token.substring(0, level);
        File toLoad = new File(dirname + "/" + l_idx + ".termMap.master");

        if (!toLoad.exists()) {
            //the token we are searching for is not mapped in disk, so we return an empty map
            return mapping;
        }
        long fileSize = toLoad.length();

        double used = mem.getUsedPer();
        double max = mem.getMaxMem();
        long fSizeMB = MemUtil.toMB(fileSize);
        double inflateRate = 2.0;
        double inflated = fSizeMB * inflateRate / max;
        double toCompare = used + inflated;

        while (toCompare >= 0.60 && !tmap_cache.isEmpty()) {
            timeOutTMap();
            System.runFinalization();
            System.gc();
        }
        loadTMap(l_idx, toLoad.getAbsolutePath());
    }

    //list of doc IDs where the term occurs
    //retrieve the token termMap
    ConcurrentHashMap<Integer, Double> docIDs = tmap_cache.get(token.substring(0, level))
            .getRight()
            .getTmap()
            .get(token);

    if (docIDs == null) {
        //the token we are searching for is not mapped in memory, so we return an empty map
        return mapping;
    }

    //update the timestamp
    tmap_cache.get(token.substring(0, level))
            .setLeft(System.currentTimeMillis());

    //insert said list into a mapping data structure
    mapping.put(token, docIDs);

    return mapping;
}
 
Example 16
Project: Limitart   File: FileScriptLoader.java   View Source Code Vote up 5 votes
/**
 * 加载一个目录下对应的全部脚本(不会加载IDynamicCode相关)
 * 
 * @param dir
 * @param scriptTypes
 * @return
 * @throws IOException
 * @throws InstantiationException
 * @throws IllegalAccessException
 * @throws ScriptException
 */
public AbstractScriptLoader<KEY> loadScriptsBySourceDir(String dir, ScriptFileType... scriptTypes)
		throws IOException, InstantiationException, IllegalAccessException, ScriptException {
	ConcurrentHashMap<KEY, IScript<KEY>> scriptMap_new = new ConcurrentHashMap<>();
	ConcurrentHashMap<KEY, File> scriptPath_new = new ConcurrentHashMap<>();
	try (GroovyClassLoader loader = new GroovyClassLoader(ClassLoader.getSystemClassLoader());) {
		File dir_root = new File(dir);
		if (!dir_root.exists()) {
			throw new IOException("scripts root dir does not exist:" + dir);
		}
		if (!dir_root.isDirectory()) {
			throw new IOException("file is not dir:" + dir);
		}
		String[] types = null;
		if (scriptTypes != null && scriptTypes.length > 0) {
			types = new String[scriptTypes.length];
			for (int i = 0; i < scriptTypes.length; ++i) {
				types[i] = scriptTypes[i].getValue();
			}
		}
		List<File> result = FileUtil.getFiles(dir_root, types);
		for (File file : result) {
			Class<?> parseClass = loader.parseClass(file);
			Object newInstance = parseClass.newInstance();
			if (newInstance instanceof IScript) {
				if (newInstance instanceof IDynamicCode) {
					continue;
				}
				@SuppressWarnings("unchecked")
				IScript<KEY> script = (IScript<KEY>) newInstance;
				KEY scriptId = script.getScriptId();
				if (scriptMap_new.containsKey(scriptId)) {
					log.error("script id duplicated,source:" + scriptPath.get(scriptId).getName() + ",yours:"
							+ file.getName());
				} else {
					scriptMap_new.put(scriptId, script);
					scriptPath_new.put(scriptId, file);
					log.info("compile script success:" + file.getName());
				}
			} else {
				throw new ScriptException("script file must implement IScript:" + file.getName());
			}
		}
		this.scriptMap = scriptMap_new;
		this.scriptPath = scriptPath_new;
	}
	return this;
}
 
Example 17
Project: openjdk-jdk10   File: FontUtilities.java   View Source Code Vote up 5 votes
public static FontUIResource getCompositeFontUIResource(Font font) {

        FontUIResource fuir = new FontUIResource(font);
        Font2D font2D = FontUtilities.getFont2D(font);

        if (!(font2D instanceof PhysicalFont)) {
            /* Swing should only be calling this when a font is obtained
             * from desktop properties, so should generally be a physical font,
             * an exception might be for names like "MS Serif" which are
             * automatically mapped to "Serif", so there's no need to do
             * anything special in that case. But note that suggested usage
             * is first to call fontSupportsDefaultEncoding(Font) and this
             * method should not be called if that were to return true.
             */
             return fuir;
        }

        FontManager fm = FontManagerFactory.getInstance();
        Font2D dialog = fm.findFont2D("dialog", font.getStyle(), FontManager.NO_FALLBACK);
        // Should never be null, but MACOSX fonts are not CompositeFonts
        if (dialog == null || !(dialog instanceof CompositeFont)) {
            return fuir;
        }
        CompositeFont dialog2D = (CompositeFont)dialog;
        PhysicalFont physicalFont = (PhysicalFont)font2D;
        ConcurrentHashMap<PhysicalFont, CompositeFont> compMap = compMapRef.get();
        if (compMap == null) { // Its been collected.
            compMap = new ConcurrentHashMap<PhysicalFont, CompositeFont>();
            compMapRef = new SoftReference<>(compMap);
        }
        CompositeFont compFont = compMap.get(physicalFont);
        if (compFont == null) {
            compFont = new CompositeFont(physicalFont, dialog2D);
            compMap.put(physicalFont, compFont);
        }
        FontAccess.getFontAccess().setFont2D(fuir, compFont.handle);
        /* marking this as a created font is needed as only created fonts
         * copy their creator's handles.
         */
        FontAccess.getFontAccess().setCreatedFont(fuir);
        return fuir;
    }
 
Example 18
Project: Reinickendorf_SER316   File: AgendaPanel.java   View Source Code Vote up 5 votes
/**
 * Returns a ConcurrentHashMap as (FileLOC count, ProjectLOC count)
 * @param projectID 
 * @param pth the path to the src folder
 * @param filePath the path to the file
 * @return must return a ConcurrentHashMap in format (FileLOC,ProjectLOC)
 */
private static synchronized ConcurrentHashMap<String, String> getLOCcountsForProject(String projectID, String pth, String filePath){
	String pathWithLOC ="{}";	//Project LOC count
	String fileWithLOC = "{}";	//Individual File LOC count
	String fileLOCWithLOC = "{}";	//Combined File LOC, Project LOC only for purposes where using setLOCcountsForProject immediately after calling this method
	//ConcurrentHashMap<String, ConcurrentHashMap<String, String>> toConfig = new ConcurrentHashMap();
	ConcurrentHashMap<String, String> chm = new ConcurrentHashMap();
	ConcurrentHashMap<String,String> toGetter = new ConcurrentHashMap();
	try{	
		
		pathWithLOC = Configuration.get(projectID).toString();	// retrieve conchashmap with JSON <Path, LOCCount>
		
		if(pathWithLOC.isEmpty() || pathWithLOC == null || !((pathWithLOC.length())>2)){
			pathWithLOC = "{\""+pth+"\":"+"\"0\"}";
			
			Configuration.put(projectID, pathWithLOC);
			Configuration.saveConfig();
		}
		Util.debug("getLOCcounts: Path With LOC: "+pathWithLOC);
		chm = sliceJSONStrIntoConcHashMap(pathWithLOC);
		
		pathWithLOC = chm.entrySet().iterator().next().getValue();
		
		
		
		fileWithLOC = Configuration.get(projectID+filePath).toString();
		chm = sliceJSONStrIntoConcHashMap(fileLOCWithLOC); 
		Util.debug("Get LOC for Project in JSON: "+pathWithLOC);
		Util.debug("Get File LOC in JSON: "+fileWithLOC);
		//if(pathWithLOC.isEmpty() || pathWithLOC == null || !(pathWithLOC.length()>0) || fileWithLOC.isEmpty() || fileWithLOC == null || !(fileWithLOC.length()>0)){
		//	fileLOCWithLOC = "{\"0\":\"0\"}";
		//}else{
			fileLOCWithLOC = "{\""+fileWithLOC+"\":\""+pathWithLOC+"\"}";
		//}
		Util.debug("FileWithProjCount: "+fileLOCWithLOC);
		
		toGetter.put(fileWithLOC, pathWithLOC);
		//toConfig.put(projectID, chm);
		
	}catch(Exception e){
		e.printStackTrace();
	}
	return toGetter;
}
 
Example 19
Project: OpenJSharp   File: FileFontStrike.java   View Source Code Vote up 5 votes
private Point2D.Float getGlyphMetrics(int glyphCode, boolean getImage) {
    Point2D.Float metrics = new Point2D.Float();

    // !!! or do we force sgv user glyphs?
    if (glyphCode >= INVISIBLE_GLYPHS) {
        return metrics;
    }
    long glyphPtr;
    if (getImageWithAdvance && getImage) {
        /* A heuristic optimisation says that for most cases its
         * worthwhile retrieving the image at the same time as the
         * metrics. So here we get the image data even if its not
         * already cached.
         */
        glyphPtr = getGlyphImagePtr(glyphCode);
    } else {
         glyphPtr = getCachedGlyphPtr(glyphCode);
    }
    if (glyphPtr != 0L) {
        metrics = new Point2D.Float();
        metrics.x = StrikeCache.unsafe.getFloat
            (glyphPtr + StrikeCache.xAdvanceOffset);
        metrics.y = StrikeCache.unsafe.getFloat
            (glyphPtr + StrikeCache.yAdvanceOffset);
        /* advance is currently in device space, need to convert back
         * into user space.
         * This must not include the translation component. */
        if (invertDevTx != null) {
            invertDevTx.deltaTransform(metrics, metrics);
        }
    } else {
        /* We sometimes cache these metrics as they are expensive to
         * generate for large glyphs.
         * We never reach this path if we obtain images with advances.
         * But if we do not obtain images with advances its possible that
         * we first obtain this information, then the image, and never
         * will access this value again.
         */
        Integer key = Integer.valueOf(glyphCode);
        Point2D.Float value = null;
        ConcurrentHashMap<Integer, Point2D.Float> glyphMetricsMap = null;
        if (glyphMetricsMapRef != null) {
            glyphMetricsMap = glyphMetricsMapRef.get();
        }
        if (glyphMetricsMap != null) {
            value = glyphMetricsMap.get(key);
            if (value != null) {
                metrics.x = value.x;
                metrics.y = value.y;
                /* already in user space */
                return metrics;
            }
        }
        if (value == null) {
            fileFont.getGlyphMetrics(pScalerContext, glyphCode, metrics);
            /* advance is currently in device space, need to convert back
             * into user space.
             */
            if (invertDevTx != null) {
                invertDevTx.deltaTransform(metrics, metrics);
            }
            value = new Point2D.Float(metrics.x, metrics.y);
            /* We aren't synchronizing here so it is possible to
             * overwrite the map with another one but this is harmless.
             */
            if (glyphMetricsMap == null) {
                glyphMetricsMap =
                    new ConcurrentHashMap<Integer, Point2D.Float>();
                glyphMetricsMapRef =
                    new SoftReference<ConcurrentHashMap<Integer,
                    Point2D.Float>>(glyphMetricsMap);
            }
            glyphMetricsMap.put(key, value);
        }
    }
    return metrics;
}
 
Example 20
Project: openjdk-jdk10   File: FileFontStrike.java   View Source Code Vote up 5 votes
private Point2D.Float getGlyphMetrics(int glyphCode, boolean getImage) {
    Point2D.Float metrics = new Point2D.Float();

    // !!! or do we force sgv user glyphs?
    if (glyphCode >= INVISIBLE_GLYPHS) {
        return metrics;
    }
    long glyphPtr;
    if (getImageWithAdvance && getImage) {
        /* A heuristic optimisation says that for most cases its
         * worthwhile retrieving the image at the same time as the
         * metrics. So here we get the image data even if its not
         * already cached.
         */
        glyphPtr = getGlyphImagePtr(glyphCode);
    } else {
         glyphPtr = getCachedGlyphPtr(glyphCode);
    }
    if (glyphPtr != 0L) {
        metrics = new Point2D.Float();
        metrics.x = StrikeCache.unsafe.getFloat
            (glyphPtr + StrikeCache.xAdvanceOffset);
        metrics.y = StrikeCache.unsafe.getFloat
            (glyphPtr + StrikeCache.yAdvanceOffset);
        /* advance is currently in device space, need to convert back
         * into user space.
         * This must not include the translation component. */
        if (invertDevTx != null) {
            invertDevTx.deltaTransform(metrics, metrics);
        }
    } else {
        /* We sometimes cache these metrics as they are expensive to
         * generate for large glyphs.
         * We never reach this path if we obtain images with advances.
         * But if we do not obtain images with advances its possible that
         * we first obtain this information, then the image, and never
         * will access this value again.
         */
        Integer key = Integer.valueOf(glyphCode);
        Point2D.Float value = null;
        ConcurrentHashMap<Integer, Point2D.Float> glyphMetricsMap = null;
        if (glyphMetricsMapRef != null) {
            glyphMetricsMap = glyphMetricsMapRef.get();
        }
        if (glyphMetricsMap != null) {
            value = glyphMetricsMap.get(key);
            if (value != null) {
                metrics.x = value.x;
                metrics.y = value.y;
                /* already in user space */
                return metrics;
            }
        }
        if (value == null) {
            fileFont.getGlyphMetrics(pScalerContext, glyphCode, metrics);
            /* advance is currently in device space, need to convert back
             * into user space.
             */
            if (invertDevTx != null) {
                invertDevTx.deltaTransform(metrics, metrics);
            }
            value = new Point2D.Float(metrics.x, metrics.y);
            /* We aren't synchronizing here so it is possible to
             * overwrite the map with another one but this is harmless.
             */
            if (glyphMetricsMap == null) {
                glyphMetricsMap =
                    new ConcurrentHashMap<Integer, Point2D.Float>();
                glyphMetricsMapRef =
                    new SoftReference<ConcurrentHashMap<Integer,
                    Point2D.Float>>(glyphMetricsMap);
            }
            glyphMetricsMap.put(key, value);
        }
    }
    return metrics;
}