简体   繁体   中英

Multi-threading Problem in Java: How to clear last element in a list when update method is no longer called?

I have this problem in a project I'm working on:

I have a list of elements sent through a server, I have a local copy of that list each time the server calls my client's update method.

The update method itself checks if the newly sent list is identical to the local copy, if not, modify the local copy. This means that if on the server, the element is no longer present, then it should be removed from the local copy.

The problem arises when the last element disappears on the server: once it does, the server stops calling the update method. This means that the local copy is left with a single element until the update method is called again, since it only gets called while the server has data to send.

Now I can't change the server architecture or the fact that it doesn't call the method when the list is empty. I can only modify the client side.

I've been experimenting with threads on my client to have some sort of thread running in parallel to clear the list if the list has not been updated in a while. This has not been working correctly or effectively, and I seem to get random results that can change completely just by changing how often the thread runs.

My main problem arises because I can't seem to find an effective way to tell if I am actively receiving data or not. I also can't seem to find a way to check if a thread is currently blocked or not.

Any ideas on how I can approach this problem? I'm not very good with threading/multi-threading and I've been bashing my head against this wall for a while now.

看到一些代码将有助于提供更具体的答案,但是如果您采用的方法在概念上有效,则可以查看Java的Timer类并创建一个TimerTask,该TimerTask调用一种方法来检查列表的最后时间更新并清除它(如果适用)。

如果发生这种情况,请使用AtomicReference。可以在此链接上找到它的好处http://www.ibm.com/developerworks/java/library/j-jtp11234/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM