目前我正在使用 LinkedList
添加所有 Command
信息。我怎样才能制作下面的 List<Command>
线程安全?我应该在这里使用任何其他选项而不是 LinkedList
?
private static List<Command> commands;
Command command = new Command();
command.setName(commandName);
command.setExecutionPercentage(Double.parseDouble(percentage));
command.setAttributeIDGet(attributeIDGet);
command.setAttributeIDSet(attributeIDSet);
command.setDataUsageCriteria(dataCriteria);
command.setUserLoggingCriteria(userLoggingCriteria);
command.setSleepTime(sleepTimeOfCommand);
我正在添加以上所有内容 command
我通过读取文本文件并将其放入 LinkedList of command
中得到的就像下面一样。所以假设如果我有 three command
然后我需要添加所有这些 three command
在一些LinkedList
这就是我正在做的。
commands.add(command);
如果我做类似下面的事情会怎样?-
Collections.synchronizedList(commands.add(command));
或者我需要做这样的事情-
commands = Collections.synchronizedList(new LinkedList<Command>());
更新:-
根据您的建议,如果我正在使用 -
private static Queue<Command> commands;
commands = new ConcurrentLinkedQueue<Command>(); // Using linked list to ensure iteration order
Command command = new Command();
command.setName(commandName);
command.setExecutionPercentage(Double.parseDouble(percentage));
command.setAttributeIDGet(attributeIDGet);
command.setAttributeIDSet(attributeIDSet);
command.setDataUsageCriteria(dataCriteria);
command.setUserLoggingCriteria(userLoggingCriteria);
command.setSleepTime(sleepTimeOfCommand);
commands.add(command);
基本上在所有初始化完成后,我需要获取 command information
。从队列中,所以我之前使用 LinkedList
做了类似的事情.但是改成ConcurrentLinkedQueue
之后, 这个get call is giving me an error
因为有一个 error line on get call
commands.get(commandWithMaxNegativeOffset);
我得到的错误-
The method get(int) is undefined for the type Queue<Command>
最佳答案
How can I make the below List thread safe? Is there any other option I should be using here instead of LinkedList?
ConcurrentLinkedQueue是并发链接队列。引用 javadocs:
An unbounded thread-safe queue based on linked nodes. This queue orders elements FIFO (first-in-first-out). The head of the queue is that element that has been on the queue the longest time. The tail of the queue is that element that has been on the queue the shortest time. New elements are inserted at the tail of the queue, and the queue retrieval operations obtain elements at the head of the queue. A ConcurrentLinkedQueue is an appropriate choice when many threads will share access to a common collection. This queue does not permit null elements.
所以你会做类似的事情:
Queue<Command> concurrentQueue = new ConcurrentLinkedQueue<Command>();
Command command = new Command();
...
concurrentQueue.add(command);
您还可以使用 Collections.synchronizedList(...)
包装当前的 List
。是执行此操作还是使用 ConcurrentLinkedQueue
取决于您需要收集的性能有多高。
// turn the commands list into a synchronized list by wrapping it
commands = Collections.synchronizedList(commands);
如果您提供有关如何使用此队列的更多信息,我们可能会在正确的 JDK 并发集合方面提供更多替代方案。
Collections.synchronizedList(commands.add(command));
您编辑了问题并询问了上述代码。它不会编译,因为 List.add(...)
返回一个 boolean 值。
关于java - 线程安全链表交替使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12043948/