Java程序性能之四

学会使用java.util.concurrent包,在开发服务器端程序更为重要,要了解的是Java应用服务器的基本框架,Java服务器大量采用线程技术,很多对象要被多个线程同时访问,采用synchronized等技术会影响性能,下边是使用并发包的两个小例子:

  1. 使用AtomicInteger记录在线的用户数,下边是我们项目中使用的一段代码:
         private   final  AtomicInteger onlineUserCount  =   new  AtomicInteger();
        
    public   void  increaseOnlineUserCount() {
            onlineUserCount.incrementAndGet();
        }
        
    public   void  decreaseOnlineUserCount() {
            onlineUserCount.decrementAndGet();
        }
        
    public   int  getOnlineUserCount() {
            
    return  onlineUserCount.get();
        }
    在HttpSessionListener中自动更新在线用户数。
  2. 使用ConcurrentHashMap 记录所有在线的注册用户数:
         private   final  ConcurrentHashMap < Long, User >  onlineUserMap  =   new  ConcurrentHashMap < Long, User > ();
        
    public   void  addOnlineUser(User user) {
            
    if (user  !=   null   &&  user.getId()  !=   null ) {
                onlineUserMap.put(user.getId(), user);
            }
        }
        
    public   void  removeOnlineUser(User user) {
            
    if (user.getId()  !=   null ) {
                onlineUserMap.remove(user.getId());
            }
        }

当然包concurrent中还提供了其他原子更新的类供使用,像AtomicLong,另外需要注意的是,concurrent中的大部分并发类不支持添加null值。

浏览本系列其他blog,错误难免,欢迎指教:

Java程序性能之一

Java程序性能之二

Java程序性能之三

你可能感兴趣的:(java,应用服务器,Blog,user,服务器,null)