我将以下代码作为OSGi模块。
运行时,我收到记录器已设置的消息:
UdpListener > setStoreLog: 'com.mine.logger.internal.storeindb.StoreLog@1c6f579'
但在此之后,run()函数中的循环表明storeLog为空
ERROR > UdpListener > run > storeLog is not available.
任何想法可能出错?
这可能是一个在线程中运行的事实吗?
package com.mine.logger.internal.udp;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Date;
import com.mine.logger.storeindb.IStoreLog;
public class UdpListener extends Thread
{
private int port;
private IStoreLog storeLog;
public void setStoreLog(IStoreLog value)
{
this.storeLog = value;
System.out.println("UdpListener > setStoreLog: '" + this.storeLog.toString() + "'");
}
public void unsetStoreLog(IStoreLog value)
{
if (this.storeLog == value) {
this.storeLog = null;
}
System.out.println("UdpListener > unsetStoreLog");
}
public UdpListener()
{
// public, no-args constructor needed for Declarative Services !!!
}
public UdpListener(int port)
{
this.port = port;
}
public void run()
{
startListener();
}
private void startListener()
{
try {
// send command
DatagramSocket socket = new DatagramSocket(port);
while (true)
{
byte[] b = new byte[1000];
DatagramPacket recvdPacket = new DatagramPacket(b, b.length);
socket.receive(recvdPacket);
System.out.println("UdpListener: Packet received. " + (new String(b)));
try
{
if (this.storeLog != null)
this.storeLog.doStore(new Date(), InetAddress.getByName("0.0.0.0"), port, 1, "UDP", b);
else
System.err.println("ERROR > UdpListener > run > storeLog is not available.");
}
catch (Exception e)
{
System.err.println("ERROR > UdpListener > run > storeLog > Exception: " + e.toString());
}
}
} catch (SocketException e) {
System.out.println("ERROR > UdpListener > run > SocketException: " + e.getMessage());
} catch (IOException e) {
System.out.println("ERROR > UdpListener > run > IOException: " + e.getMessage());
} catch (Exception e) {
System.out.println("ERROR > UdpListener > run > Exception: " + e.getMessage());
}
}
}
答案 0 :(得分:2)
您的代码不是线程安全的。 storeLog字段由多个线程读取和写入,没有任何同步。如果您有一个可由多个线程读取和写入的可变字段,则必须确保始终安全地访问该字段 读取和写入。我高度为任何编写Java代码的人推荐优秀的Java Concurrency in Practice http://www.javaconcurrencyinpractice.com/。
答案 1 :(得分:-2)
通过将商店日志移至单独的类
来解决