Posts

Showing posts with the label thread-safety

Can ConcurrentLinkedDeque have a fixed size and overwrite old elements?

Can ConcurrentLinkedDeque have a fixed size and overwrite old elements? If I got this right ConcurrentLinkedDeque acts as a stack right if you use pollLast() ? pollLast() Now my issue is that I need a set size of ConcurrentLinkedDeque. My producer doesn't stop, so even if I have 16GB of ram I will run out eventually. SO is it possible to se a fixed size ? My implementation: ConcurrentLinkedDeque<String> queue = new ConcurrentLinkedDeque<>(); Producer (Thread 1): runs queue.add(line); Consumer (Thread 2): runs queue.pollLast(); queue.add(line); queue.pollLast(); Please note that both threads run in a while true loop . This is because of the requirements. That is why I am using ConcurrentLinkedDeque and not ArrayBlockingQueue or SynchronousQueue because it is non-blocking. ConcurrentLinkedDeque ArrayBlockingQueue SynchronousQueue Also do I need to declare anything synchronised ? synchronised Use a fixed size BlockingQueue which would all...

Use sychronized or not below code generating same hashcode for all threads. How?

Use sychronized or not below code generating same hashcode for all threads. How? "we make the global access method synchronized so that only one thread can execute getInstance method at a time" without using synchronized keyword below code acting like threadsafe already. Car.java public class Car { private static Car car; private Car() { // TODO Auto-generated constructor stub } public static Car getInstance(){ if(car==null){ car=new Car(); } return car; } } Test.java public class Test { public static void main(String args) { Thread t1=new Thread(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName()+" Running"); System.out.println(Car.getInstance().hashCode()); System.out.println(Thread.currentThread().getName()+" Finishing"); } }); t1.start(); Thread t2=new Thread(new Runnable() { @Override public...