Currently I am using LinkedList to add all the Command information. How can I make the below List<Command> thread safe? Is there any other option I should be using here instead of 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);
I am adding all the above command that I am getting by reading from the text file and putting it into the LinkedList of command just like below. So suppose if I have three command then I need to add all those three command in to some LinkedList which is what I was doing.
commands.add(command);
What If I do something like below?-
Collections.synchronizedList(commands.add(command));
or I need to do something like this-
commands = Collections.synchronizedList(new LinkedList<Command>());
Update:-
As per your suggestion, If I am using –
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);
And after sometime basically when all the initialization has been done, I need to get the command information from the Queue, So I was doing something like this previously with the use of LinkedList. But after chaning to ConcurrentLinkedQueue, this get call is giving me an error as there is a error line on get call
commands.get(commandWithMaxNegativeOffset);
Error I am getting-
The method get(int) is undefined for the type Queue<Command>
ConcurrentLinkedQueue is a concurrent linked queue. To quote from the javadocs:
So you’d do something like:
You can also wrap your current
Listusing theCollections.synchronizedList(...). Whether to do this or useConcurrentLinkedQueuedepends on how high performance you need the collection to be.If you provide some more information about how you are using this queue, we can provide possibly more alternatives in terms of the proper JDK concurrent collection.
You edited your question and asked about the above code. It won’t compile since
List.add(...)returns a boolean.