zoukankan      html  css  js  c++  java
  • Java练习题

    1.实现一个类似于ConcurrentHashMap的分段加锁

    import java.util.HashMap;
    import java.util.Map;
    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;
    
    public class SegmentLock {
    	private static final int DEFAULT_INITIAL_CAPACITY = 16;
    
    	private static final int MAXIMUM_CAPACITY = 1 << 30;
    
    	private static final int MAX_SEGMENTS = 1 << 16; // slightly conservative
    
    	final int segmentMask;
    
    	final int segmentShift;
    
    	private Pair<Lock, Map<String, Counter>>[] segmentLocks;
    
    	public SegmentLock(final int concurrentLevel) {
    		int size = 1;
    		int shift = 0;
    		while (size < concurrentLevel) {
    			size <<= 1;
    			shift += 1;
    		}
    
    		segmentMask = size;
    		segmentShift = 32 - shift;
    
    		for (int i = 0; i < size; i++) {
    			segmentLocks[i] = new Pair(new ReentrantLock(), new HashMap<String, Counter>());
    		}
    	}
    
    	public Pair<Lock, Map<String, Counter>> get(final String key) {
    		return segmentLocks[(hash(key.hashCode()) >> segmentShift) & segmentMask];
    	}
    
    	private static int hash(int h) {
    		h += (h << 15) ^ 0xffffcd7d;
    		h ^= (h >>> 10);
    		h += (h << 3);
    		h ^= (h >>> 6);
    		h += (h << 2) + (h << 14);
    		return h ^ (h >>> 16);
    	}
    
    	static class Pair<Left, Right> {
    		private final Left left;
    		private final Right right;
    
    		public Pair(final Left left, final Right right) {
    			this.left = left;
    			this.right = right;
    		}
    	}
    
    	static class Counter {
    		private int count;
    
    		public int increaseAndGet() {
    			return ++count;
    		}
    
    		public int decreaseAndGet() {
    			return --count;
    		}
    
    		public int get() {
    			return count;
    		}
    	}
    }
    

      

    2.怎样初始化一个泛型数组?

       new ArrayList<String>[]();

  • 相关阅读:
    Linux系统的关机、重启、睡眠
    Java 读写Properties配置文件
    Java识别操作系统
    Java DES 加解密("DES/CBC/PKCS5Padding")
    Java获取本机IP
    编写SHELL脚本--编写简单脚本
    配置yum软件仓库(redhat 7.0)
    简单的redis测试
    Seaslog安装和参数配置
    mac使用phpize进行安装的时候碰到的问题
  • 原文地址:https://www.cnblogs.com/wuxinliulei/p/5464707.html
Copyright © 2011-2022 走看看