如何使用ConcurrencyHashmap另一个类或主方法?

时间:2016-04-08 11:44:45

标签: java netty

public class keyClientHandler extends ChannelInboundHandlerAdapter{

public static ConcurrentHashMap<String, String> keyTable = new ConcurrentHashMap<>();

String information;
String hashMapKey; 
String hashMapValue; 

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

    // do something

    keyTable.put(hashMapKey, hashMapValue);

    System.out.println(keyTable.size()); //size = 268
}

public static ConcurrentHashMap<String,String> getKeyTable() {

    return keyTable;
}

另一课使用:

public static void main(String[] args) {

    ConcurrentHashMap<String, String> map = keyClientHandler.getKeyTable();

    System.out.println(map.size()); //size=0

}

当我尝试在另一个类或main方法中使用填充的concurrentMap时,它返回空。 我如何使用其他类的Concurentmap?

3 个答案:

答案 0 :(得分:0)

我们如何解释您的问题?

    public static ConcurrentHashMap<String, String> keyTable = new ConcurrentHashMap<>();

静态concurrentHashMap已在class KeyClientHandler中定义。您打算检索地图对象并从另一个类的main method打印地图的大小。现在正如你所说,你的程序运行并输出0作为输出。这意味着您在访问地图方面没问题。如果无法从另一个类的主要方法访问concurrentHashMap,则应该有编译错误

有什么方法可以证明这更好?

我认为需要进行以下改进。首先,您不需要在此处使用静态地图或静态方法。我们也可以在没有静态的情况下证明这一点。尝试运行此示例,这是对代码的轻微修改。

import java.util.concurrent.ConcurrentHashMap;

class ChannelHandlerContext {
    // some class
}

class KeyClientHandler{
    public ConcurrentHashMap<String, String> keyTable = new ConcurrentHashMap<>();

    String information;
    String hashMapKey; 
    String hashMapValue; 

    KeyClientHandler() {

    }

    public void setKeyValue(String key, String value){
        hashMapKey = key;
        hashMapValue = value;   
    }

    public  void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // do something
        keyTable.put(hashMapKey, hashMapValue);
        System.out.println(keyTable.size()); //size = 268
    }

    public ConcurrentHashMap<String,String> getKeyTable() {
       return keyTable;
    }
}

public class TestConcurrentHashMap {
    public static void main(String[] args) {
        KeyClientHandler keyClientHandler = new KeyClientHandler();
        keyClientHandler.setKeyValue("apples", "fruit");
        ConcurrentHashMap<String, String> map = keyClientHandler.getKeyTable();
        try {
            keyClientHandler.channelRead(null, null); // not the best thing
            System.out.println(map.size()); //size=1
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

输出:
1

答案 1 :(得分:0)

我的项目是套接字编程。我使用Netty Framework。我发送TCP客户端并收到消息发送给其他客户端。

服务器:

public class KeyClient {

static final String HOST = System.getProperty("host", "...");
static final int PORT = Integer.parseInt(System.getProperty("port", "..."));

public static void keyClientStart() throws InterruptedException {

    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                 .channel(NioSocketChannel.class)
                 .option(ChannelOption.TCP_NODELAY, true)
                 .handler(new keyClientInitializer());

        ChannelFuture future = bootstrap.connect(HOST, PORT).sync();
        future.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }

}
}

KeyClientInitializer:

public class keyClientInitializer extends ChannelInitializer<SocketChannel> {

@Override
protected void initChannel(SocketChannel ch) throws Exception {

    ChannelPipeline pipeline = ch.pipeline();

    pipeline.addLast(new LoggingHandler(LogLevel.INFO));

    pipeline.addLast(new FixedLengthFrameDecoder(32));

    pipeline.addLast(new keyClientHandler());
}
}

KeyClientHandler:

public class keyClientHandler extends ChannelInboundHandlerAdapter{

public static ConcurrentHashMap<String, String> keyTable = new ConcurrentHashMap<>();

String information;
String hashMapKey; 
String hashMapValue; 

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

    ByteBuf buffer = (ByteBuf) msg;

    byte[] receivedKey = byteBufToByteArray(buffer);

    information = DatatypeConverter.printHexBinary(receivedKey);

    // do something
    // ...

    keyTable.put(hashMapKey, hashMapValue); //map has elements



}

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    cause.printStackTrace();
}

public static ConcurrentHashMap<String,String> getKeyTable() {
       return keyTable;
 }

private byte[] byteBufToByteArray(ByteBuf buffer) {

    byte[] receivedKey;
    int offset;
    int length = buffer.readableBytes();

    if (buffer.hasArray()) {
        receivedKey = buffer.array();
        offset = buffer.arrayOffset();
    } else {
        receivedKey = new byte[length];
        buffer.getBytes(buffer.readerIndex(), receivedKey);
        offset = 0;
    }

    return receivedKey;
}

}

测试类:

public class AppMain {

public static void main(String[] args) throws InterruptedException {

    KeyClient.keyClientStart();

    ConcurrentHashMap<String, String> map = keyClientHandler.getKeyTable(); // is empty

}

当我添加'System.out.println(keyTable);'在keyClientHandler中,我看到了地图值。 Output

答案 2 :(得分:0)

在我的情况下,将CHM对象保存在其他类上是可以的,您可以检查:

  • System.out.println(keyTable.size());之后调用channelRead(...)?你打印哪个类的键?如果是下一个频道处理程序,您应该致电ctx.fireChannelRead(msg);吗?
  • 其他方式可以打印CHM hashCode(),如果它们相同,则表示相同的对象。