一个统计流量的JAVA程序;
利用缓存, 每5分钟更新一下DB的流量统计的字段, 
调用:ViewNumCounter .addArtViewCnt(artId);
帮我考虑一下多线程的环境中会有什么问题, 如有问题改一下程序?public class ViewNumCounter extends TimerTask {
 static Map videoMap = new HashMap(); private static VideoViewNumCounter instance = null; private ViewNumCounter () {
 } /**
  * Construct method, to keep there is only one instance
  * @return
  */
 public static ViewNumCounter getInstance() {
  if (instance == null) {
   instance = new ViewNumCounter ();
   Timer t = new Timer();
   t.schedule(instance, 0, 5 * 60 * 1000);
  }
  return instance;
 } /**
  * Insert the article view number to DB and dump the vidio view count map
  */
 public void run() {  Iterator it = videoMap.entrySet().iterator();  while (it.hasNext()) {
   java.util.Map.Entry entry = (java.util.Map.Entry) it.next();
   Long videoId = (Long) entry.getValue();
   Integer accessNum = (Integer) entry.getKey();
   logger.fine("Artcle [" + videoId + "]" + "access num is " + accessNum);   try {
   // insert into database
   addVideoViewCnt(videoId, accessNum);
   } catch (Exception ex) {   }
  }  videoMap.clear();
 } /**
  * To add up the article view count
  * @param videoId
  */
 public static synchronized void addArtViewCnt(Long videoId) {
  Integer accessNum = Integer.valueOf(0);
  if (videoMap.containsKey(videoId)) {
   accessNum = (Integer) videoMap.get(videoId);
  }
  accessNum = Integer.valueOf(accessNum.intValue() + 1);
 }
}

解决方案 »

  1.   

    你好像没有把新的数值放回去。那个addArtViewCnt有什么作用呢?
      

  2.   

    addArtViewCnt就是访问页面时,把videoId对映的浏览数加1啊, 
    videoMap是这样存储的:
    KEY     --》VALUE
    videoId -->浏览数
      

  3.   

    我是说你没有把新的值放进去,那个addArtViewCnt其实啥作用也没有。
      

  4.   

    那方法加上 videoMap.put(accessNum, accessNum);
      

  5.   

    public static synchronized void addArtViewCnt(Long videoId) {
      Integer accessNum = Integer.valueOf(0);
      if (videoMap.containsKey(videoId)) {
      accessNum = (Integer) videoMap.get(videoId);
      }
      accessNum = Integer.valueOf(accessNum.intValue() + 1);videoMap.put(videoId, accessNum);
      

  6.   

    public static ViewNumCounter getInstance() { 
      if (instance == null) { 
      instance = new ViewNumCounter (); 
      Timer t = new Timer(); 
      t.schedule(instance, 0, 5 * 60 * 1000); 
      } 
      return instance; 
    } 多线程获取的时候其实是有点问题。简单的可以加用synchronized,对性能会有影响。可以用double-check 模式。