Will volatile work for Collections and objects?
Trying to understand the theory about volatile
.
They say, volatile
provides happens-before, so changes done in thread 1 should be visible in thread 2.
What if we will put volatile for Collection? Will java provide visibility in Thread 2 for changes done in Thread 1 ? And why?
public class Vol {
volatile List<String> list = new ArrayList<>();
// thread 1
public void put(String s) {
list.add(s);
}
// thread 2
public List<String> get(){ // all changes are visible? "Why" for No\Yes answer
return list;
}
}
do you know?
how many words do you know
See also questions close to this topic
-
Read each name in Array list to create seperate object for
I have a file that has student names, age, and an id number. I have a student class that holds the everything above for each student object. I stored all the names, id numbers. and age separately in an array list. Now im trying to assign the info to create a student object.
public class Student { private String lName; private int idNumber; private int age; public Student() { lName = ""; idNumber = 0; age = 0; } public Student(String l, int i, int a) { lName = l; idNumber = i; age = a; } public void setName(String last) { lName = last; } public String getName() { return lName; } public void setIdNum(int num) { idNumber = num; } public int getIdNum() { return idNumber; } public void setAge(int a) { age = a; } public int getAge() { return age; } }
My Text File looks something like this: This info is stored in parallel array lists. I don't quite get how to implement this into an object to pass it into my second contractor method.
Josh 2134 19 Smith 5256 21 Rogers 9248 19 Andrew 7742 20
Here's what I've tried;
public static void main(String[] args) { String file = "studentData.txt"; Scanner reader = new Scanner(file); ArrayList<String> lastNames = lNames(file); ArrayList<Integer> idNumbers = idNum(file); ArrayList<Integer> ageList = ages(file); Scanner input = new Scanner(System.in); Student s1 = new Student(); // confused about how to implement this constructor with the textile info for (int i = 0; i<idNumbers.size(); i++) { Student user = new Student(lastNames.get(i), idNumbers.get(i), ageList.get(i)); } //user enters idNumber to display age System.out.println("Enter ID Number"); //exception handling to be added int idNum = input.nextInt(); for (int i = 0; i<idNumbers.size(); i++) { if (idNum == idNumbers.get(i)) { s1.setAge(ageList.get(i)); System.out.println(s1.getAge()); } } }
-
Using EdittextPreference for Goto search
sorry for my poor English. I want to use EditTextPreference in my bottom nav like the pic below, ![screenshot][1]
I have recycleview xml in my project with in many sub cardview layouts(which is scrollable) and I want to create item in the bottom nav which is called "Goto". When the "Goto" item is clicked i want it to pop-up like the screenshot. And when user enters a number(according to the cardviews i.e if the number of cardview is 40 user must enter 1-40) I want to search the cardview by its ID. Thank you and I hope u got it, If u have any questions let me know [1]: https://i.stack.imgur.com/grK8P.jpg
My xml format look like this. As you see in the blow since the cardviews are huge in number it is not cool to scroll all the way down that is why i need Goto item in the bottom nav to search it by its ID when the user click number in the EditTextPreference as u see in the screenshot. i.e The screenshot is not from my app
<LinearLayout> <LinearLayout> <androidx.cardview.widget.CardView> <RealtiveLayout> <Textview/> <RealtiveLayout> </androidx.cardview.widget.CardView> </LinearLayout> <LinearLayout> <androidx.cardview.widget.CardView> <RealtiveLayout> <Textview/> <RealtiveLayout> </androidx.cardview.widget.CardView> </LinearLayout> <LinearLayout> <androidx.cardview.widget.CardView> <RealtiveLayout> <Textview/> <RealtiveLayout> </androidx.cardview.widget.CardView> </LinearLayout> <LinearLayout> <androidx.cardview.widget.CardView> <RealtiveLayout> <Textview/> <RealtiveLayout> </androidx.cardview.widget.CardView> </LinearLayout> .. .. .. .. many more..
-
How to get remaining time of the day in java?
I would like to calculate the time remaining for next day 00:00:00 from the current date time.
For e.g. time difference between 2
022-05-07T05:49:41.883807900Z
and2022-05-08T00:00:00Z
Expected answer:
18:10:19
or 65419 (in seconds).How can I achieve this with efficiently using java 8?
-
Write a program using Multithreading in C++ while using pthread_join()?
Write a program in the shell using threads. Each thread must be doing one of the tasks mentioned below. One task must be completed and then another task should be started. Use pthread_join() system call to make the thread wait for the other thread's completion. Get the input at the start and use these numbers in all threads. The numbers must consist of four digits at least. i.e 1234. a) Finding the largest of three numbers b) Reversing the largest number c) Sum of individual digits of a 4-digit number (1234 -> 1+2+3+4=10)
-
Multithreading using springboot
I’m new to multithreading and I want to know how to approach it for my code, currently files are getting generated and processed into fielder using single thread hence unable to handle bulk file generation abs this needs to be handled using multithreading . How do I approach this ? Using java 11 and xml format springboot approach .
-
storing the HashMap key value pair by code refactoring
I am trying to refactor the below method and return
Map<Integer, List<OrderReference>> response = new HashMap<>();
instead ofMap<DepartmentReference, Integer>
I want to store the error number we are currently storing as value in the below method as key in the new refactored method and value will beList<OrderReference>
private Map<DepartmentReference, Integer> getBulkOrders(String type, List<BulkSpecification> bulkSpec) { Map<DepartmentReference, Integer> departmentOrders = new HashMap<>(); for (BulkSpecification bulkSpecification : bulkSpec) { List<Order> orders = new ArrayList<>(); List<OrderReference> ordRefs = bulkSpecification.getOrderReferences(); for (OrderReference ordRef : ordRefs) { Order order = new Order(); order.setSpecification(bulkSpecification.getSpecification()); DepartmentReference departmentReference = OrderPersist.getDealerInformation(ordRef.getVistaReference()); order.setOrderReference(ordRef); if (!Order.validateOrder(order, type)) { departmentOrders.put(departmentReference, 3); } else { OrderPersist orderPersist = new OrderPersist(); try { MyOrderResponse myOrderResponse = orderPersist.bulkorderer(order, getUserCode(), getMessage(getMarket(), getLanguage(), 4), type); if (myOrderResponse.getUpdateStatus().isSuccessful()) { departmentOrders.put(departmentReference, 0); orders.add(order); } else { departmentOrders.put(departmentReference, 6); } } catch (OrderError orderError) { Exception exception = orderError.getOrderException(); int errorNo = 10; if (exception != null && exception instanceof SQLException && ((SQLException) exception).getErrorCode() == GENERIC_SQL_ERRNO) { errorNo = 1178; } departmentOrders.put(departmentReference, errorNo); } } } } return departmentOrders; }
-
Kotlin Collection indexOf using reference equality ===
In Kotlin,
indexOf(x)
called on aCollection
returns the index of the first element thatequals(x)
(structural equality==
)How can one get the index based on referential equality (
===
) instead? -
Arduino MEGA configurable PORT manipulation fails when PIN is volatile int
I have a project in Arduino Mega where i want the user to be able to configure the output pins for XYZE axes of a motion controller from a Python GUI. I am using direct port manipulation for fast pin toggling and in order to define each PORT and PIN i am using variables for both. So far i am experimenting only at Arduino side.
PORTS:
volatile uint8_t *PORTX_STEP; volatile uint8_t *PORTX_DIR; volatile uint8_t *PORTY_STEP; volatile uint8_t *PORTY_DIR; volatile uint8_t *PORTZ_STEP; volatile uint8_t *PORTZ_DIR; volatile uint8_t *PORTE_STEP; volatile uint8_t *PORTE_DIR; ..... void configure_output(){ PORTX_STEP = &PORTF; PORTY_STEP = &PORTF; PORTX_DIR = &PORTF; PORTY_DIR = &PORTF; PORTZ_STEP = &PORTL; PORTZ_DIR = &PORTL; PORTE_STEP = &PORTA; PORTE_DIR = &PORTA; } .... void setup(){ configure_output(); } .... void service_routine(){ /// **Timer interrupt routine** bitRead(buffer1.byte_1[j],0) = 0 or 1 *PORTX_DIR = *PORTX_DIR | (bitRead(buffer1.byte_1[j],0)<<XDIR); *PORTX_STEP = *PORTX_STEP | (bitRead(buffer1.byte_1[j],1)<<XSTEP); *PORTY_DIR = *PORTY_DIR | (bitRead(buffer1.byte_1[j],2)<<YDIR); *PORTY_STEP = *PORTY_STEP | (bitRead(buffer1.byte_1[j],3)<<YSTEP); *PORTZ_DIR = *PORTZ_DIR | (bitRead(buffer1.byte_1[j],4)<<ZDIR); *PORTZ_STEP = *PORTZ_STEP | (bitRead(buffer1.byte_1[j],5)<<ZSTEP); *PORTE_DIR = *PORTE_DIR | (bitRead(buffer1.byte_1[j],6)<<EDIR); *PORTE_STEP = *PORTE_STEP | (bitRead(buffer1.byte_1[j],7)<<ESTEP); }
While PORT configuration works something stange happens when configure PINs
This works:
int XSTEP=0;//PF0 int YSTEP=6;//PF6 int ZSTEP=3;//PL3 int ESTEP=4;//PA4 int XDIR=1;//PF1 int YDIR=7;//PF7 int ZDIR=1;//PL1 int EDIR=6;//PA6`
while this NOT:
volatile int XSTEP=0;//PF0 volatile int YSTEP=6;//PF6 volatile int ZSTEP=3;//PL3 volatile int ESTEP=4;//PA4 volatile int XDIR=1;//PF1 volatile int YDIR=7;//PF7 volatile int ZDIR=1;//PL1 volatile int EDIR=6;//PA6
Link to full source code: github
Any ideas?
-
Java JIT a static non-volatile value changed , the access loop becomes a hundred times longer
There is a branch judgment on a non volatile static bool value in the loop. When the bool value is modified by other threads, the execution time of the whole loop becomes a hundred times longer, and jstack shows that the thread runs on the line acces
sample:
package test; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; public class StaticTest { static boolean tag = true; static HashSet<Integer> set = new HashSet<>(); static boolean getTag(int i) { if (!tag) { return set.contains(i); } return true; } public static void main(String[] args) throws InterruptedException { for (int i = 0; i < 225 * 225 * 4; i++) { set.add(ThreadLocalRandom.current().nextInt(0, 225 * 225 * 4)); } Thread.sleep(5000); for (int i = 0; i < 128; i++) { Thread t = new Thread(() -> { while (true) { long start = System.currentTimeMillis(); HashMap<Integer, Boolean> iMap = new HashMap<>(); for (int j = 0; j < 225 * 225 * 4; j++) { if (getTag(j)) { iMap.put(j, true); } else { iMap.put(j, false); } } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } }); t.start(); } Thread.sleep(TimeUnit.MINUTES.toMillis(3)); tag = true; System.out.println(new Date(System.currentTimeMillis())); while (true) { Thread.sleep(10000); } } }
-
What serves the same purpose of Java volatile in C++?
I learned the
volatile
keyword in Java. It serves as a mean to ensure visibility in other threads when a variable is written by one particular thread. It does this by removing machine caches of certain variables and disabling CPU instruction reordering under some cases at each write.I noted that
volatile
exists in C++, while it serves different purposes. I wonder how C++ implements cache coherence and other things that goes withvolatile
in Java.