java - can I access a static Arraylist of Vector of another thread? in this example? -
having problems accessing static vector thread , class in thread. 1 class gui class called lotteryplay, has static vector called packarray, , other class called multithreader , part of shown below, runs in different thread. ideas on wrong?
the thing think of trying access static vector thread. possible?
@override public void run() { try { out = new printwriter(socket.getoutputstream(), true); in = new bufferedreader(new inputstreamreader(socket.getinputstream())); system.out.println("streams setup new thread\n"); line = ""; while((line = in.readline())!= null){ this.messagefromclient(line); if(!(counter > 1)){ textsplitter(line); socketpack = new socketpack(socket, timestamp, address); lotteryplay.packarray.add(socketpack); <<<----null pointer exception system.out.println("size of packarray " + lotteryplay.packarray.size()); system.out.println(); system.out.println("pakc array "+ lotteryplay.packarray); } system.out.println("from client: " + line.trim() + "\n"); } // end while loop
exception in thread "thread-3" java.lang.nullpointerexception at.com.lotterygame.multithreader.run(multithreader.java:55) @ java.lang.thread.run(thread.java:662)
the fact you're getting nullpointerexception
suggests lotteryplay.packarray
null. need make sure it's initialized before use it.
if really want keep static variable, i'd advise make final
, e.g.
public static final vector<socketpack> packarray = new vector<socketpack>();
however, i'd advise redesign application avoid requiring static variables. think needs data, , pass appropriately. static variables make code harder reason , test.
additionally, note although each operation in vector
individually synchronized, doesn't make thread-safe. example, can't safely iterate on vector
without synchronization, otherwise 1 thread modify while you're iterating. should consider collections in java.util.concurrent
.
Comments
Post a Comment