Java 如何使用并发映射另一个类或主方法? public类keyClientHandler扩展ChannelInboundHandlerAdapter{ 公共静态ConcurrentHashMap键表=新ConcurrentHashMap(); 字符串信息; 字符串hashMapKey; 字符串hashMapValue; @凌驾 public void channelRead(ChannelHandlerContext ctx,Object msg)引发异常{ //做点什么 put(hashMapKey,hashMapValue); System.out.println(keyTable.size());//size=268 } 公共静态ConcurrentHashMap getKeyTable(){ 返回键表; }

Java 如何使用并发映射另一个类或主方法? public类keyClientHandler扩展ChannelInboundHandlerAdapter{ 公共静态ConcurrentHashMap键表=新ConcurrentHashMap(); 字符串信息; 字符串hashMapKey; 字符串hashMapValue; @凌驾 public void channelRead(ChannelHandlerContext ctx,Object msg)引发异常{ //做点什么 put(hashMapKey,hashMapValue); System.out.println(keyTable.size());//size=268 } 公共静态ConcurrentHashMap getKeyTable(){ 返回键表; },java,netty,Java,Netty,另一类用途: public class keyClientHandler extends ChannelInboundHandlerAdapter{ public static ConcurrentHashMap<String, String> keyTable = new ConcurrentHashMap<>(); String information; String hashMapKey; String hashMapValue; @Override pu

另一类用途:

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;
}
publicstaticvoidmain(字符串[]args){
ConcurrentHashMap=keyClientHandler.getKeyTable();
System.out.println(map.size());//size=0
}
当我尝试在另一个类或main方法中使用填充的concurrentMap时,它返回空。 如何使用其他类中的Concurentmap?

我们如何解释您的问题? 输出:

1

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

服务器:

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();
        }
    }
}
KeyClientInitializer:

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扩展了通道初始值设定项{
@凌驾
受保护的void initChannel(SocketChannel ch)引发异常{
ChannelPipeline=通道管道();
addLast(新的LoggingHandler(LogLevel.INFO));
addLast(新的固定长度帧解码器(32));
addLast(新的keyClientHandler());
}
}
KeyClientHandler:

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());
}
}
public类keyClientHandler扩展ChannelInboundHandlerAdapter{
公共静态ConcurrentHashMap键表=新ConcurrentHashMap();
字符串信息;
字符串hashMapKey;
字符串hashMapValue;
@凌驾
public void channelRead(ChannelHandlerContext ctx,Object msg)引发异常{
ByteBuf缓冲区=(ByteBuf)味精;
字节[]receivedKey=byteBufToByteArray(缓冲区);
信息=DatatypeConverter.printHexBinary(receivedKey);
//做点什么
// ...
keyTable.put(hashMapKey,hashMapValue);//映射有元素
}
@凌驾
public void exceptionCaught(ChannelHandlerContext ctx,可丢弃原因)引发异常{
cause.printStackTrace();
}
公共静态ConcurrentHashMap getKeyTable(){
返回键表;
}
专用字节[]字节字节字节数组(字节缓冲区){
字节[]receivedKey;
整数偏移量;
int length=buffer.readableBytes();
if(buffer.hasArray()){
receivedKey=buffer.array();
偏移量=buffer.arrayOffset();
}否则{
receivedKey=新字节[长度];
getBytes(buffer.readerIndex(),receivedKey);
偏移量=0;
}
返回接收键;
}
}
测试等级:

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;
}

}
公共类AppMain{
公共静态void main(字符串[]args)引发InterruptedException{
KeyClient.keyClientStart();
ConcurrentHashMap=keyClientHandler.getKeyTable();//为空
}

当我在keyClientHandler中添加'System.out.println(keyTable);'时,我看到了映射值。

在我的案例中,可以在其他类中保留CHM对象,您可以检查:

  • System.out.println(keyTable.size());
    是否在
    channelRead(…)
    之后调用?您在哪个类上打印密钥?如果是下一个通道处理程序,是否应调用
    ctx.fireChannelRead(msg);
  • 另一种方法是打印CHM
    hashCode()
    ,如果它们相同,则表示相同的对象

似乎工作正常。您得到的引用不是空的。它是空的,但这只是意味着还没有任何东西将数据放入其中。这是非常基本的内容。关于这个问题,CHM也没有任何特定的内容。您似乎在两个不同的虚拟机上运行您的程序,您必须在同一个JVM中使用相同的映射。注意:如果您需要我们作为一个分布式映射,比如纪事映射,它可以在多个JVM之间共享。我认为他只有一个VM,但是
keyClientHandler.getKeyTable();
是一个静态方法(其名称不好的类类似于变量名)访问(public)静态CHM。没有任何通道读取发生,我怀疑他是在他的头上。我同意@Kayaman。不要认为他是指不同的VM。首先感谢你的回答,但我的问题是不同的。我不需要把map放在另一个类中。我必须在channelRead方法中填充concurrentmap,我想在下一个类中使用这个map值er类。@AtakanCoşar,您将从何处调用channelRead方法。在您共享的示例中,我看不到任何调用。如果调用了它,并且您填充了hashMap,则结果将显示在主方法中。当您进行此调用时,如何知道您的clientHandler是否收到了数据。当我添加'System.out.println(keyTable)';'在keyClientHandler中,我看到映射值。尝试使用:for(字符串键:keyTable.keySet()){System.out.println(键+“”+keyTable.get(键));}输出:E201:E201:FF0246DA2AFBE35C0453A0000000000000000E201:E201:FF00D25BE25083AE54E6D0000000000000000E201:E201:EA15C0000000000000000D3CFC66883B10135 E201:E201:FF0164FF3216398F416A2000000000000000I在keyClientHandler中接收到密钥,但我不使用其他类的密钥。@DROY
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());
}
}
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

}