lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
Java
I am very familiar with functional langauges such as Scheme , and Haskell . I 'm trying to solve a problem in Java and struggling , possibly because I 'm still in a functional mindset.I want to write : with an interface like : and a class implementing the interface like : so that the first method can call the appropria...
public void doQueryAndStoreData ( String query , < ? extends Collection > storeIn ) { /* make a jdbc query , get ResultSet */ ResultSet rset = ... ; ProcessResultSet proc = new ProcessResultSet ( ) ; proc.process ( rset , storeIn ) ; /* clean up */ } private interface IProcessResultSet < C > { public void process ( Res...
Java Higher Order Polymorphic Function
Java
When I try to execute this , I get This is method which takes stringas the output . Why not `` This is in method which takes object '' ? Object can also be null and string can also be null , why does n't it invoke first method ?
class Another { public void method ( Object o ) { System.out.println ( `` This is in method which takes object '' ) ; } public void method ( String s ) { System.out.println ( `` This is method which takes string '' ) ; } } public class NewClass { public static void main ( String args [ ] ) { Another an = new Another ( ...
Why is the output like this ?
Java
I want to create a cached thread pool , but it acts as a fixed one . Currently I have this code : If I run the code I get output : Meaning only 2 threads are doing all the work and no new worker threads are added to the pool . Should n't the threadpool spawn more threads if tasks are waiting in queue ( up to 10 in my c...
public class BackgroundProcesses { public static void main ( String [ ] args ) throws InterruptedException , ExecutionException { //ExecutorService threadPool2 = Executors.newCachedThreadPool ( ) ; ExecutorService threadPool = new ThreadPoolExecutor ( 2 , 10 , 180 , TimeUnit.SECONDS , new LinkedBlockingQueue < > ( ) ) ...
Thread pool not resizing
Java
BackgroundI have an ordered set of data points stored as a TreeSet < DataPoint > . Each data point has a position and a Set of Event objects ( HashSet < Event > ) .There are 4 possible Event objects A , B , C , and D. Every DataPoint has 2 of these , e.g . A and C , except the first and last DataPoint objects in the se...
public class ProbabilityCalculator { private Double p ( DataPoint right , Event rightEvent , DataPoint left , Event leftEvent ) { // do some stuff } private Double f ( DataPoint right , Event rightEvent , NavigableSet < DataPoint > points ) { DataPoint left = points.lower ( right ) ; Double result = 0.0 ; if ( left.isL...
Optimisation of recursive algorithm in Java
Java
I have a problem in this block of code that I saw in oracles site.Can someone explain it for me ?
Action updateCursorAction = new AbstractAction ( ) { boolean shouldDraw = false ; public void actionPerformed ( ActionEvent e ) { if ( shouldDraw = ! shouldDraw ) { // < -- -- - here is my problem , what 's this condition for ? // is n't it always false ? drawCursor ( ) ; } else { eraseCursor ( ) ; } } } ; new Timer ( ...
Redundant Condition
Java
I have a ConcurrentMap < String , SomeObject > object . I want to write a method that would return the SomeObject value if it exists , or create a new SomeObject , put it in the Map , and return it if it does n't exist.Ideally , I could use ConcurrentMap 's putIfAbsent ( key , new SomeObject ( key ) ) , but that means ...
public SomeValue getSomevalue ( String key ) { SomeValue result = concurrentMap.get ( key ) ; if ( result ! = null ) return result ; synchronized ( concurrentMap ) { SomeValue result = concurrentMap.get ( key ) ; if ( result == null ) { result = new SomeValue ( key ) ; concurrentMap.put ( key , result ) ; } return resu...
Do I need to synchronize ConcurrentMap when adding key only if needed ?
Java
I 'm doing a little test to understand how metaspace memory ( Java 8 onwards ) works.When I create 100,000 classes dynamically the metaspace memory is growing ( obviously ) but heap memory is going up too.Can someone explain to me why this occurs ? PS : I 'm running the test with 128 MB of heap and 128 MB of metaspace....
@ Testpublic void metaspaceTest ( ) throws CannotCompileException , InterruptedException { ClassPool cp = ClassPool.getDefault ( ) ; System.out.println ( `` started '' ) ; for ( int i = 0 ; i < = 100000 ; i++ ) { Class c = cp.makeClass ( `` br.com.test.GeneratedClass '' + i ) .toClass ( ) ; Thread.sleep ( 1 ) ; if ( i ...
Why is heap memory going up together with metaspace in Java 8 ?
Java
I have a project built with Gradle version 6.4 and JDK 8 . I 'm trying to use the Gradle plugin for Test Fixtures ( java-test-fixtures ) but I have some issues with the dependencies.According to the Gradle page linked above , the project should be structured like this : While the build.gradle.kts file has the following...
core-module -- src -- main -- java -- test -- java -- testFixtures -- java dependencies { api ( `` com.my.external.project:1.0 '' ) // ... more API dependencies testFixturesCompileOnly ( project ( `` : core-module '' ) ) testFixturesApi ( `` junit : junit:4.12 '' ) // ... more test dependencies } testFixturesImplementa...
Gradle test fixtures plugin and core module dependencies
Java
I am writing an interpreter for the language BrainfuckI used the command linethe bf program is supposed to put out 00 to FF in hex , but it puts outwhere the ... represent a sequence of +1 in hexthe 3f replaces 80 to 9f , and i have no idea whySource : the output on the command prompt is
java bfinterpreter/BFInterpreter > output.bin 00 01 02 03 04 05 06 ... 7f 3f 3f 3f 3f 3f ... a0 a1 a2 ... ff package bfinterpreter ; /** * * @ author Nicki von Bulow */public class BFInterpreter { private char [ ] program ; private StringBuilder output ; private byte [ ] input ; private short inputPosition ; private sh...
Brainfuck interpreter misbehaving
Java
When I compile with this compiler code : I do n't get any errors.but when i compiler with this codeI do get errorsthe alert.java is the first file
@ echo offjavac -d bin -sourcepath src/*.java src/sign/*.java src/Alert.javapause @ echo offjavac -d bin -sourcepath src/*.java src/sign/*.javapause
Javac fails to find symbol when wildcard is used , but works when .java file is manually specified
Java
This is the code I have : And IntelliJ will warn me for the last statement above with the message : Condition 'bar ! = null ' is always 'true ' . This inspection analyzes method control and data flow to report possible conditions that are always true or false , expressions whose value is statically proven to be constan...
private void foo ( Bar bar ) { Session session = null ; Class entityClazz = null ; try { entityClazz = Hibernate.getClass ( bar ) ; if ( bar ! = null ) { entityClazz = Hibernate.getClass ( bar ) ;
Why is IntelliJ telling me that reference can not be null in this situation ?
Java
UpdateI 've updated the question with newer code suggested by fellow SO users and will be clarifying any ambiguous text that was previously there.Update # 2I only have access to the log files generated by the application in question . Thus I 'm constrained to work within the content of the log files and no solutions ou...
REGEX = `` ScriptExecThread ( \\ ( [ 0-9 ] +\\ ) ) .* ? ( finished|starting ) '' //in java Set started , finished for ( int i=log.size ( ) -1 ; i > =0 ; i -- ) { if ( group ( 2 ) .contains ( `` starting '' ) started.add ( log.get ( i ) ) else if ( group ( 2 ) .contains ( `` finished '' ) finished.add ( log.get ( i ) } ...
Text Search based algorithm not behaving as intended
Java
I have a an array of bytes I 'm calculating a checksum for in Java . And I 'm trying to convert it to Kotlin . But the problem is that I am getting different values when calculating the -128 & 0xff in Java than it 's equivalent in Kotlin . When passing in the -128 , when I make the calculation in Java , it gives me a p...
public class Bytes { public static byte [ ] getByteArray ( ) { return new byte [ ] { -128 } ; } public static int getJavaChecksum ( ) { int checksum = 0 ; for ( Byte b : getByteArray ( ) ) { checksum += ( b & 0xff ) ; } return checksum ; } } fun getKotlinChecksum ( array : ByteArray ) : Byte { var checksum = 0 for ( b ...
Converting Java bitwise `` and '' operator over to Kotlin
Java
As some of you are aware , C++ allows doing this : with the function get implemented something like : Is something similar possible in Java ? More specifically , I 'd like to encapsulate array indexing logic in a function ( in a high-performance way ) .
get ( array , 5 ) = 5 ; int & get ( int* array , int index ) { return array [ index ] ; }
Is it possible to return an L-value from a function
Java
Is there historical reasons to the two ambiguous List.remove ? List.remove ( int ) List.remove ( Object ) It seems like terrible design to me.For a List < Integer > it just seems really confusing.EDIT : Everybody seems pretty fine with this . Let me precise things a bit.Let 's say I have a List < Boolean > .Though idx ...
Integer idx = Integer.valueOf ( 2 ) ; list.remove ( idx )
Why is List.remove overloaded the way it is ?
Java
I 'm trying to generate Scaladoc for my code with the scala-maven-plugin 3.0.2 ( Scala Version 2.9.2 ) . When I usethen I do n't get documentation for the private types and elements of my Scala code . I checked with the plugin documentation , but I ca n't find an option for that.Strangely , the scaladoc plugin does gen...
mvn scala : doc
How to document private elements in scaladoc with scala-maven-plugin ?
Java
Basically i have built an appointment scheduler webapp using java servlets.It relies heavily on javas Calendar.The whole thing was developed on my macbook running mountain lion with jdk 1.6.Now when testing it on my pc i have had some strange results.Running : on the PC will output : Yet on the mac it will output : As ...
System.out.println ( `` selected = `` +selected ) ; Calendar now = Calendar.getInstance ( ) ; System.out.println ( `` a `` +now.getTime ( ) ) ; now.setTimeInMillis ( selected ) ; System.out.println ( `` b `` +now.getTime ( ) ) ; now.set ( Calendar.MILLISECOND,0 ) ; now.set ( Calendar.SECOND,0 ) ; now.set ( Calendar.MIN...
Java Calendar , acts differently OSX Windows
Java
What is the difference between these 2 codes : AndBoth of them have the same output.Thank you .
Arraylist < Integer > listofIntegers = new Arraylist < Integer > ( ) ; listofIntegers.add ( 666 ) ; System.out.println ( `` First Element of listofIntegers = `` + listofIntegers.get ( 0 ) ) ; Arraylist < Integer > listofIntegers = new Arraylist < Integer > ( ) ; listofIntegers.add ( Integer.ValueOf ( 666 ) ) ; System.o...
What is difference between of listofIntegers.add ( ValueOf ( 50 ) ) ; and listofIntegers.add ( 50 ) ; in Java
Java
I am attempting to change the following array line into an ArrayList that will function the same way : I changed it to this but it is not functioning properly : I thought this was how an ArrayList was created
private String [ ] books = new String [ 5 ] ; private ArrayList < String > ( Arrays.asList ( books ) )
Changing an Array to an ArrayList
Java
I am working on sorting a map by values code using java 8.I have done most of the thing but I am not getting how to convert the list to map using java 8 features
public class SortMapByValue { public static void main ( String [ ] args ) { HashMap < String , Integer > map = new HashMap < > ( ) ; map.put ( `` A '' , 3 ) ; map.put ( `` V '' , 1 ) ; map.put ( `` Anss '' , 9 ) ; map.put ( `` D '' , 5 ) ; map.put ( `` E '' , 2 ) ; map.put ( `` F '' , 10 ) ; HashMap < String , Integer ...
Convert List to map using java 8
Java
Greetings noble community , I want to have the following loop : This will run in parallel on a shared-memory quad-core computer using threads . The two alternatives below are being considered for the code to be executed by these threads , where tid is the id of the thread : 0 , 1 , 2 or 3 . ( for simplicity , assume MA...
for ( i = 0 ; i < MAX ; i++ ) A [ i ] = B [ i ] + C [ i ] ; for ( i = tid ; i < MAX ; i += 4 ) A [ i ] = B [ i ] + C [ i ] ; for ( i = tid* ( MAX/4 ) ; i < ( tid+1 ) * ( MAX/4 ) ; i++ ) A [ i ] = B [ i ] + C [ i ] ;
Efficiency of Multithreaded Loops
Java
I 'm trying to convert an AVLTree implementation into a heap style array and am having some problems with generics : At the line AVLNode [ ] bArray = new AVLNode [ size ] ; I get the following error : `` Can not create a generic array of MyAVLTree.AVLNode '' I do n't see what I 'm doing wrong . Any help ?
public class MyAVLTree < K extends Comparable < ? super K > , E > implements OrderedDictionary < K , E > { class AVLNode implements Locator < K , E > { // ... } // ... . public Locator < K , E > [ ] toBSTArray ( ) { AVLNode [ ] bArray = new AVLNode [ size ] ; makeArray ( root , 0 , bArray ) ; // recursion return bArray...
Java Generics : Can not create an array of a nested class
Java
I 'm using a static analyzer in Eclipse to examine my code . One class , foo , has an inner class , bar . I am getting the following error : Why is this an error ? As long as the outer class uses the inner class is n't that sufficient to make this information hiding useful and correct ? The inner class is not static .
JAVA0043 Inner class 'bar ' does not use outer class 'foo '
What is wrong with an inner class not using an outer class in Java ?
Java
For an enumeration defined in a class , like Is the enumeration a static nested class ( https : //docs.oracle.com/javase/tutorial/java/javaOO/nested.html ) ? It seems to be the case judging from the syntax used to refer to it . Or is it a non-static nested class ( an inner class ) ?
class OuterClass { public enum Method { GET , PUT , POST , DELETE ; } }
Enums defined in a class is a static nested class ?
Java
I wish to disable links of a page I am loading to my WebView object . My code works perfectly on my emulator with api 25 , but not on my phone with 23 api.This is the code that blocks the links of my WebView : I am setting my WebViewClient to be an object of type NoLinksWebViewClient . It does the trick on the emulator...
public class NoLinksWebViewClient extends WebViewClient { @ Override public boolean shouldOverrideUrlLoading ( WebView view , WebResourceRequest request ) { return true ; } }
Disabling WebView links works on emulator but no on device
Java
Consider my custom extended hashmap : Why does n't this work since CustomHashMap is child of HashMap ? But this works : And also it works when adding ( put ) an CustomHashMap into the customs Map.It seems weird that not specifying the generics at initialization works , but it does n't otherwise .
public class CustomHashMap extends HashMap < String , Object > { ... } Map < String , HashMap < String , Object > > customs = new LinkedHashMap < String , CustomHashMap > ( ) ; Map < String , HashMap < String , Object > > customs = new LinkedHashMap ( ) ; customs.put ( `` test '' , new CustomHashMap ( ) ) ;
Inheritance does n't work with passed as generic type
Java
I 'm using the diamond operator to initiate objects within a list . However as the number of array objects increases , compile time increases from few seconds to hours . My eclipse auto build made my eclipse non-responsive . I then noticed it is a javac issue . When I replace all < > with < String , List < Category > >...
List < Pair < String , List < Category > > > categoryMappings = null ; public void reloadStaticData ( ) { // Left one is the provider 's category and right one is ours try ( UoW luow = CoreModule.getInstance ( UoW.class ) ) { CategoryRepo categoryRepo = luow.getCategoryRepo ( ) ; categoryMappings = Arrays.asList ( // N...
Java object initialization with diamond operator terrible javac compile time performance
Java
I know there is an intrinsic overhead of the JVM , and I wanted to do further research to see exactly what the overhead is from.Using the YourKit profiler I was able to find that there are giant int [ ] filled with seemingly random information . My guess was that these store some performance metrics and other things th...
public final class Main { public static void main ( String [ ] args ) throws InterruptedException { Thread.sleep ( Long.MAX_VALUE ) ; } }
Why does the JVM use giant int [ ] of all 0 's ?
Java
At the company I work for there 's a document describing good practices that we should adhere to in Java . One of them is to avoid methods that return this , like for example in : I would have such a class so that I 'm able to write : I 've seen such idiom many times , like in StringBuilder and do n't find anything wro...
class Properties { public Properties add ( String k , String v ) { //store ( k , v ) somewhere return this ; } } properties.add ( `` name '' , `` john '' ) .add ( `` role '' , '' swd '' ) . ... properties.add ( `` name '' , `` john '' ) ; properties.add ( `` role '' , `` swd '' ) ;
What 's wrong with returning this ?
Java
I.e. , inandwill a1 be garbage collected or is the reference to a1.s permitting it from being collected ( and I should rather do a deep copy , a2.s = new String ( a1.s ) ) ? Thanks a lot in advance !
class A { public String s ; } A a1 = new A ( ) ; a1.s = `` bla '' ; A a2 = new A ( ) ; a2.s = a1.s ; a1 = null ;
Will an element be garbage collected if there is a reference to its field ?
Java
I can able to loop through all elements of List like below : I want to print the user object only for first element but I should loop for all elements in list.How to achieve that ?
userList.forEach ( user - > { System.out.println ( user ) ; } ) ;
Java List forEach Lamba expressional - first elements and loop through all elements
Java
The following code gives me : The local variable str may not have been initializedSo , I gave str a null value , and it worked but I 'm still wondering why the one on the docs work without initializing the value first , I 've triple checked and I do n't think I have any typos :
public class experiment { public static void main ( String [ ] args ) { int day = 1 ; String str ; switch ( day ) { case 1 : str = `` nice '' ; break ; } System.out.println ( str ) ; } } public class SwitchDemo { public static void main ( String [ ] args ) { int month = 8 ; String monthString ; switch ( month ) { case ...
Switch statement uninitialized variable
Java
I 'm using LIBSVM . In the download package is a svm_toy.java file . I could not find out how it works . Here is the source code : Could someone give me an example or explanation ? I also would like to scale my training data . Where is the right place to scale ? Thanks
import libsvm . * ; import java.applet . * ; import java.awt . * ; import java.util . * ; import java.awt.event . * ; import java.io . * ; /** * SVM package * @ author unknown * */public class svm_toy extends Applet { static final String DEFAULT_PARAM= '' -t 2 -c 100 '' ; int XLEN ; int YLEN ; // off-screen buffer Imag...
How to use the 'svm_toy ' Applet example in LibSVM ?
Java
I try to write a gradle task with kotlin , this is my code . : GreetingTask.ktbuild.gradleGreetingTaskTestWhen running the test now it results in a : Which is this line : What i would like to know is : Where does this issue come from and how do i fix it ?
class GreetingTask : DefaultTask ( ) { @ TaskAction fun greet ( ) { println ( `` greet ! '' ) } } buildscript { repositories { mavenCentral ( ) } dependencies { classpath `` org.jetbrains.kotlin : kotlin-gradle-plugin:0.12.613 '' } } apply plugin : `` kotlin '' dependencies { compile `` org.jetbrains.kotlin : kotlin-st...
java.lang.VerifyError creating a gradle task with kotlin
Java
I have been trying to figure out my mistake in the Sudoku backtracking solver for three days . The problem is from leetcode Sudoku Solver . My solver is based on the deduction in the attached picture . The problem is that my board is changed even if a path from root to leaf is invalid . In other words , after it goes t...
public void sudokuSolver ( char [ ] [ ] board ) { for ( int i = 0 ; i < board.length ; i++ ) { for ( int j = 0 ; j < board.length ; j++ ) { if ( board [ i ] [ j ] == ' . ' ) { // find the first ' . ' as root helper ( i , j , board ) ; return ; } } } } private boolean helper ( int row , int col , char [ ] [ ] board ) { ...
Stuck in Sudoku backtracking solver ( Java )
Java
BACKGROUND : I 'm trying to learn algorithms and java . Running a grid of 320x320 , 100 trials runs about 5 times faster than a non-recursive Quick-Union implementation . However , beyond above a grid of about 400x400 ( 160,000 sites ) , I have stack overflow errors.I understand that java is not optimized for tail-recu...
| -- -- -- -- -- -| -- -- -- -- -- -| -- -- -- -- -- -- | -- -- -- -- -- -- -| -- -- -- -- -- -- -|| N | Recursive | Recursive | Quick-Union | Quick-Union || ( sites ) | time | 2x Ratio | time | 2x Ratio ||===========|===========|============|=============|=============|| 196 | 35 | | 42 | || 400 | 25 | 0.71 | 44 | 1.0...
How to evaluate the utility of a recursive algorithm in Java ?
Java
Here is a sample code which make me a little missing : As you see , I create a LeakThread and finish the WindowLeakActivity at doInBackground ( ) method.In order to prevent window leak error , I have to check if the Activity has been finished at onPostExecute ( ) method.That make me a little missing.I have following qu...
package com.leak ; import android.app.Activity ; import android.app.ProgressDialog ; import android.os.AsyncTask ; import android.os.Bundle ; public class WindowLeakActivity extends Activity { @ Overrideprotected void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; new LeakThread ( ) .e...
When would Activity 's instance die ?
Java
I want to access all the methods ( non-abstract+abstract ) from Class A.So i extended Class A , but here in Class B i want to access all non-abstract methods and only 10 abstract method - as I dont want to implement rest of the abstract methods of class B.Problem:1.I ca n't extend Class B because i have already extende...
abstract class A { public void m1 ( ) { //do stuff } public void m2 ( ) { //do stuff } // +30 more non abstract methodspublic abstract void n1 ( ) ; public abstract void n2 ( ) ; // +30 more abstract method } abstract class B { public void a1 ( ) { //do stuff } public void a2 ( ) { //do stuff } // +30 more non abstract...
how can i implement specific method from two different abstract class ?
Java
In a book I 'm studying , they show this Java code : This code is used to dynamically load a Java class . The book goes on : unloading modules raises an issue . A class loader can not unload a class . Unloading a class requires unloading the class loader itself . This is why programmers .. tend to define several class ...
Class c = ClassLoader.getSystemClassLoader ( ) .loadClass ( name ) ; Class type = this.getClass ( ) .getClassLoader ( ) .loadClass ( name ) ; Object obj = type.newInstance ( ) ;
How is the following Java code useful , in the realm of autonomic computing ?
Java
I have an array tab1 that contains some strings and another array that could contains all element of array tab1.how do I can do this to avoid repeating same element of tab1 : I would like to say : tab2 = { tab1 , '' HO '' , ... } any idea ? thanks ,
String [ ] tab1 = { `` AF '' , '' HB , '' ER '' } String [ ] tab2 = { `` AF '' , '' HB , '' ER '' , '' HO '' , '' NF '' , '' BB '' , '' CD '' , '' PO '' }
array containing another
Java
Is it possible for an interface to be accessible only in the same package and child packages ? I have defined an interface with default modifier : Now I have a child package where I want to define a class which implements BaseDao . So I wrote this code : But I get this error : BaseDao can not be resolved to a typeSo is...
package com.mycompany.myapp.dao ; import java.io.Serializable ; interface BaseDao < T , Id extends Serializable > { public void create ( T t ) ; public T readById ( Id id ) ; public void update ( T t ) ; public void delete ( T t ) ; } package com.mycompany.myapp.dao.jpa ; import java.io.Serializable ; public class Base...
Is it possible for an interface to be accessible only in the same package and child packages ?
Java
I 'm trying to use a Fill Flood algorithm for make a Cube Painting tool for an app.This is the code of the algorithm : } This is the part where I handle the touch event on my ImageView : The problem is that the coordinates are not accurate . I mean , wherever I touch the image it gets painted in other part in which I h...
public class QueueLinearFloodFiller { protected Bitmap image = null ; protected int [ ] tolerance = new int [ ] { 0 , 0 , 0 } ; protected int width = 0 ; protected int height = 0 ; protected int [ ] pixels = null ; protected int fillColor = 0 ; protected int [ ] startColor = new int [ ] { 0 , 0 , 0 } ; protected boolea...
Getting touch coordinates not accurate in ImageView FloodFill Algorithm
Java
Consider the floating point number 0.644696875 . Let 's convert it to a string with eight decimals using Java and C : Javaresult : 0.64469688try it yourself : http : //tpcg.io/oszC0wCresult : 0.64469687try it yourself : http : //tpcg.io/fQqSRFThe QuestionWhy is the last digit different ? BackgroundThe number 0.64469687...
import java.lang.Math ; public class RoundExample { public static void main ( String [ ] args ) { System.out.println ( String.format ( `` % 10.8f '' ,0.644696875 ) ) ; } } # include < stdio.h > int main ( ) { printf ( `` % 10.8f '' , 0.644696875 ) ; //double to string return 0 ; }
Why do C and Java round floats differently ?
Java
I am trying to figure out this line in a thread dumpWhat is that address after runnable ? Looks like a stack address is it the top of the stack ?
`` RMI TCP Connection ... .. '' daemon prio=3 tid=0x0000000106f12000 nid=0x1e10 runnable [ 0xfffffffe48dfe000 ]
interpreting line in thread dump
Java
I came over an article regarding the new Flow related interfaces in Java9 . Example code from there : As you can see , onNext ( ) requests one new item to be pushed . Now I am wondering : if onSubscribe ( ) requested , say 5 items and after the first item gets delivered , request ( 1 ) is called like aboveIs the server...
public class MySubscriber < T > implements Subscriber < T > { private Subscription subscription ; @ Override public void onSubscribe ( Subscription subscription ) { this.subscription = subscription ; subscription.request ( 1 ) ; //a value of Long.MAX_VALUE may be considered as effectively unbounded } @ Override public ...
Flow programming : subscriber and publisher to keep track of count ?
Java
I want to fetch a data from xml Using Xquery with starts with function.data.xmlNow I want to fetch that name which has employee @ id=title @ id and name @ value starts with 'vC'.I have written this xquery for the same.Please see below but getting error-this is error-
< data > < employee id=\ '' 1\ '' > < name value=\ '' vA-12\ '' > A < /name > < title id=\ '' 2\ '' > Manager < /title > < /employee > < employee id=\ '' 2\ '' > < name value=\ '' vC-12\ '' > C < /name > < title id=\ '' 2\ '' > Manager < /title > < /employee > < employee id=\ '' 2\ '' > < name value=\ '' vB-12\ '' > B ...
Fetching data from xml Using Xquery with starts with function
Java
I need to integrate a custom spell-checker into an existing Java application without an Automation API.It should work like this : In the external application A , the user opens a window , where he/she enters some text . In that window there is a button `` Spellchecker '' .When the user presses the `` Spellchecker '' bu...
Toolkit.getDefaultToolkit ( ) .addAWTEventListener ( new MyAWTEventListener ( ) , AWTEvent.MOUSE_MOTION_EVENT_MASK ) ; while ( true ) { Thread.sleep ( 1 ) ; } private void queuePushingExperiment ( ) throws InterruptedException , InvocationTargetException { EventQueue queue = Toolkit.getDefaultToolkit ( ) .getSystemEven...
How to detect when a button has been pressed in an external Java application ?
Java
I was trying to solve this question : Given an array of integers with only 3 unique numbers print the numbers in ascending order ( with their respective frequencies ) in O ( n ) time.I wanted to solve it without using the counting sort algorithm , So what I thought is I could just do a for loop and insert the numbers i...
public static void printOut ( int [ ] arr ) { Map < Integer , Integer > hm=new HashMap < Integer , Integer > ( ) ; for ( int num : arr ) { if ( hm.containsKey ( num ) ) { hm.put ( num , hm.get ( num ) +1 ) ; } else { hm.put ( num,1 ) ; } } for ( Map.Entry < Integer , Integer > entry : hm.entrySet ( ) ) { System.out.pri...
Explanation about HashMap hash algorithm in this example
Java
This bug is present in the latest 1.7 and 1.8 versions of the JDK ( 7u72 , 8u25 ) . Required : jackson-databind 2.5.0 . Tested on Linux x86_64 ( Ubuntu 14.10 to be precise ) .Code : This produces an invalid zip file : I have originally opened the bug on Jackson 's issue tracker even though it really is n't the culprit ...
public static void main ( final String ... args ) throws IOException { final Map < String , String > map = Collections.singletonMap ( `` create '' , `` true '' ) ; final Path zipfile = Paths.get ( `` /tmp/foo.zip '' ) ; Files.deleteIfExists ( zipfile ) ; final URI uri = URI.create ( `` jar : '' + zipfile.toUri ( ) ) ; ...
Bug in Oracle 's JDK zip filesystem , how do you write an SSCCE to reproduce it ?
Java
Let 's say I have a Fraction class : And this is what the bytecode of the above method turns out to be : I 'm trying to understand why instruction at position 3 was put there in the first place . I 'd say we 'd only need to do the following to make it work : Why is not so ?
class Fraction { ... /** Invert current fraction */ public Fraction inverse ( ) { return new Fraction ( den , num ) ; } ... } 0 new # 1 < xyzTestes/system/fraction/Fraction > 3 dup 4 aload_0 5 getfield # 16 < xyzTestes/system/fraction/Fraction.den > 8 aload_0 9 getfield # 14 < xyzTestes/system/fraction/Fraction.num > 1...
Why does the following code translate to a new + dup op instructions in java bytecode ?
Java
I am currently using a 3rd party java library , `` foo '' , that has jni dependencies . The jni dependency also utilizes softlinks . The directory structure looks something likeHow do I package the .jar & .so , with softlink , and upload to my local nexus `` 3rd party '' repository ? There is a similar question but unf...
foo/ /foo.jar /libfoo.so - > libfoo.so.1.0 /libfoo.so.1.0
Adding A 3rd Party JNI Library to Nexus
Java
Seeing as Valentine 's Day is fast approaching , I decided to create a heart . So I found this heart from mathematica.se : I played around in Mathematica ( solved for z , switching some variables around ) to get this equation for the z-value of the heart , given the x and y values ( click for full-size ) : I faithfully...
import static java.lang.Math.cbrt ; import static java.lang.Math.pow ; import static java.lang.Math.sqrt ; ... public static double heart ( double xi , double yi ) { double x = xi ; double y = -yi ; double temp = 5739562800L * pow ( y , 3 ) + 109051693200L * pow ( x , 2 ) * pow ( y , 3 ) - 5739562800L * pow ( y , 5 ) ;...
How do I fix this heart ?
Java
I want to create the following GUI with Java Swing.Since I 'm not experienced enough with Java Swing , I 'm not sure how to exactly recreate that GUI.I 've tried using GridLayout which looks like this : I 've tried other LayoutManagers but due to my inexperience , I could n't get anything even remotely resembling the G...
import java.awt . * ; import javax.swing . * ; public class GUITest extends JFrame { public GUITest ( ) { super ( `` Testing Title '' ) ; Container pane = getContentPane ( ) ; pane.setLayout ( new GridLayout ( 3,1 ) ) ; pane.add ( getHeader ( ) ) ; pane.add ( getTextArea ( ) ) ; pane.add ( getButtonPanel ( ) ) ; } publ...
How do I create the following GUI in Java Swing ?
Java
So , I need to write a compiler scanner for a homework , and thought it 'd be `` elegant '' to use regex . Fact is , I seldomly used them before , and it was a long time ago . So I forgot most of the stuff about them and needed to have a look around . I used them successfully for the identifiers ( or at least I think s...
private void readNumber ( Token t ) { t.str = `` '' + ch ; // force conversion char -- > String final Pattern pattern = Pattern.compile ( `` [ 0-9 ] * '' ) ; nextCh ( ) ; // get next char and check if it is a digit Matcher match = pattern.matcher ( `` '' + ch ) ; while ( match.find ( ) & & ch ! = EOF ) { t.str += ch ; ...
Java regex and pattern matching : finding `` blanks '' in pattern which do not include them ?
Java
I 'm trying to understand how positions/offsets work in HTMLDocument . Position/offset semantics are described here . My interpretation is that these are indices in the sequence of on-screen characters represented by the HTMLDocument.Consider the example HTML from the HTMLDocument documentation : When I open this HTML ...
< html > < head > < title > An example HTMLDocument < /title > < style type= '' text/css '' > div { background-color : silver ; } ul { color : red ; } < /style > < /head > < body > < div id= '' BOX '' > < p > Paragraph 1 < /p > < p > Paragraph 2 < /p > < /div > < /body > < /html > import java.io.StringReader ; import j...
Meaning of position or offset in HTMLDocument text
Java
I 'm new to Java , my question is on big-O complexity.For a ) , it is clearly O ( n^2 ) for a nested loop.however , for b ) , with sum++ operation at the end , and complications in the nested loop , does that change the its Big-O complexity at all ?
for ( int i = 0 ; i < n ; i++ ) for ( int j=0 ; j < n ; j++ ) int sum = 0 ; for ( int i = 1 ; i < = n ; i++ ) for ( int j = n ; j > 0 ; j /= 2 ) sum++ ;
Big-O complexity java
Java
why java did n't choose this signature < T > Stream < T > Stream.generate ( Supplier < ? extends T > supplier ) over this one < T > Stream < T > Stream.generate ( Supplier < T > supplier ) ? I mean the below example ( does n't compile ) is correct as a supplier of strings is also valid in a stream of charsequences no ?
Supplier < String > constantHello = ( ) - > `` Hello '' ; long count = Stream. < CharSequence > generate ( constantHello ) .count ( ) ;
Problems understanding the Stream.generate static method signature in java 8
Java
Would someone please explain why { } is written after a String array declaration ? Thanks .
private final String [ ] okFileExtensions = new String [ ] { `` csv '' } ;
Strange string array declaration Syntax
Java
I have a code here : As you can see I have mentioned the error . I 'm trying to create a quickfix for this in eclipse jdt ui . But i 'm unable to get the superclass node of the class B that is Class TestOverride.I tried the following codeIn here I got parentClass as TestOverride only . But when I checked this is not of...
public class TestOverride { int foo ( ) { return -1 ; } } class B extends TestOverride { @ Override int foo ( ) { // error - quick fix to add `` return super.foo ( ) ; '' } } if ( selectedNode instanceof MethodDeclaration ) { ASTNode type = selectedNode.getParent ( ) ; if ( type instanceof TypeDeclaration ) { ASTNode p...
How do i get the Superclasses node in Eclipse jdt ui ?
Java
The javadoc of Spliterator mentions that : A Spliterator may traverse elements individually ( tryAdvance ( ) ) or sequentially in bulk ( forEachRemaining ( ) ) . Then we go to the javadoc of tryAdvance ( ) which says that : If a remaining element exists , performs the given action on it , returning true ; else returns ...
action.accept ( arg1 ) ; action.accept ( arg2 ) ; return true ; // deque is a Deque < Iterator < T > > @ Overridepublic boolean tryAdvance ( final Consumer < ? super T > action ) { Iterator < T > iterator ; T element ; while ( ! deque.isEmpty ( ) ) { iterator = deque.removeFirst ( ) ; while ( iterator.hasNext ( ) ) { e...
Is there any danger in making the action .accept ( ) more than one element in an implementation of Spliterator 's .tryAdance ( ) ?
Java
I tried to write the following code as a stream : this code works fine.But when I rewrite it like this it does n't work anymore : The Optional which I get back from the stream has no values in it . Why ? EDITWhen I try this ( I still get two devices back from getDevices ( ) ) : the testList is empty . So it seems like ...
AbstractDevice myDevice = null ; for ( AbstractDevice device : session.getWorkplace ( ) .getDevices ( ) ) { if ( device.getPluginconfig ( ) .getPluginType ( ) .getId ( ) == 1 ) { myDevice = device ; } } myDevice = session.getWorkplace ( ) .getDevices ( ) .stream ( ) .filter ( s - > s.getPluginconfig ( ) .getPluginType ...
Why does this stream return no element ?
Java
I am trying to parse a pacs.003 ISO20022 formatted xml file . I have the XSD for this and using XMLBeans have created the required Java classes . The problem I am having is that I am not able to read an element from the XML and keep getting a NullPointerException . I have searched for similar problems but most result i...
< S2SDDDnf : FIToFICstmrDrctDbt xmlns= '' urn : iso : std : iso:20022 : tech : xsd : pacs.003.001.02 '' > < GrpHdr > < MsgId > DDA160802AASW006543 < /MsgId > < /GrpHdr > < /S2SDDDnf : FIToFICstmrDrctDbt > public static void main ( String [ ] args ) { XmlOptions xmlOptions = new XmlOptions ( ) ; xmlOptions.setUseDefault...
Apache XmlBeans NullPointerException
Java
So i 'm a little confused about a change in Java 8 - List.sort - bear with me as the confusion will become apparent.I have Java 8 JDK installed and running Eclipse with the Project in question set to compile in 1.6 ( Windows environment ) .Throughout my code I 've been doing ( Example extends BaseExample ) : Despite co...
public static final Comparator < BaseExample > sortByLevel_DESC = new Comparator < NavItemBase > ( ) { ... } ; List < Example > examples = new ArrayList < Example > ( ) ; examples.sort ( sortByLevel_DESC ) ; examples.stream ( ) .filter ( e - > e.active ( ) ) .collect ( Collectors.toList ( ) ) ;
List.sort ( ) NoSuchMethodException 1.6 vs 1.8
Java
I 've read and came to realize myself that entities ( data objects - for JPA or serialization ) with injections in them is a bad idea . Here is my current design ( all appropriate fields have getters and setter , and serialVersionUID which I drop for brevity ) .This is the parent object which is the head of the entity ...
public class State implements Serializable { List < AbstractCar > cars = new ArrayList < > ( ) ; List < AbstractPlane > planes = new ArrayList < > ( ) ; // other objects similar to AbstractPlane as shown below } public abstract class AbstractPlane implements Serializable { long serialNumber ; } public class PropellorPl...
How to alter the design so that entities do n't use injections ?
Java
In Java , when can one `` get away '' with not using synchronized on variables that are read/write for multiple concurrent threads ? I read about a couple of surprising concurrency bugs : double-checked-locking and hash-maps , and have always used synchronize by default in shared read/write cases , however , I started ...
T getFoo ( ) { if ( this.foo == null ) { this.foo = createFoo ( ) // createFoo is always thread safe . } return this.foo ; }
When is it safe to not synchronize read/write variables ?
Java
given a generic interface : and a generic class that implements the interfacewhy does the following work ? I expected the T type parameter of the method interfaceMethod as defined in class A to constrain the method to arguments that have the same type as that supplied to the constructor of A . ( in this case String ) ....
public interface I < E > { public int interfaceMethod ( E s ) ; } public class A < T > implements I < T > { private T val ; public A ( T x ) { val = x ; } public int interfaceMethod ( T val ) { // looks like T should be of the same type as instance variable 'val ' return 0 ; } } public class Run { public static void ma...
Java generics , interfaces and type constraints
Java
As the title says , given a stock of integers 0-9 , what is the last number I can write before I run out of some integer ? So if I 'm given a stock of , say 10 for every number from 0 to 9 , what is the last number I can write before I run out of some number . For example , with a stock of 2 I can write numbers 1 ... 1...
public class Numbers { public static int numbers ( int stock ) { int [ ] t = new int [ 10 ] ; for ( int k = 1 ; ; k++ ) { int x = k ; while ( x > 0 ) { if ( t [ x % 10 ] == stock ) return k-1 ; t [ x % 10 ] ++ ; x /= 10 ; } } } public static void main ( String [ ] args ) { System.out.println ( numbers ( 4 ) ) ; } } 9 9...
Given a stock of integers 0-9 , what is the last number I can write before I run out of some integer ?
Java
Reproducer : Warning emitted : Access to enclosing method w ( ) from the type IDs is emulated by a synthetic accessor methodI understand what synthetic methods are - what I do not get is how they come into play with enums - I would expect enum instances to have all private methods I define in the enum . Are instances r...
enum IDs { ID { @ Override void getId ( ) { w ( ) ; // warning here } } ; void getId ( ) { } private static void w ( ) { } }
Are enum instances `` enclosed '' in the enum type in java ?
Java
In given example : will return : c= -1183744630 , why ? How to fix that ?
int a , b , c ; a = 2111000333 ; b = 1000222333 ; c = a + b ; System.out.println ( `` c= `` + c ) ;
How to fix an error with adding integers in Java ?
Java
I have a List < UserMeal > collection , where UserMeal has : I need to convert it into Map < LocalDate , Integer > . The key of the map must be the dateTime ( converted to LocalDate ) of the UserMeal item in the collection.And the value of the map has to be sum of calories.I can not figure it out how to do this with st...
public class UserMeal { private final LocalDateTime dateTime ; private final int calories ; public UserMeal ( LocalDateTime dateTime , int calories ) { this.dateTime = dateTime ; this.calories = calories ; } public LocalDateTime getDateTime ( ) { return dateTime ; } public int getCalories ( ) { return calories ; } } it...
Collectors.toMap ( ) keyMapper
Java
What has changed in tomcat 7.0.42 - > 7.0.47 at EL-Escaping ? I have an include tag : dataview.jspx containsIn tomcat 7.0.42 it renders to this : But in 47 it renders this : what changed ? and how can i now output my js-variable ?
< jsp : include page= '' /WEB-INF/jsp/elements/dataview.jspx '' > < jsp : param name= '' customParameter '' value= '' { id : $ { object.id } , action : \ ' $ { action } \ ' } '' / > < /jsp : include > < script type= '' text/javascript '' > var customParameter = ' $ { param.customParameter } ' ; < /script > var customPa...
What changed in tomcat 7.0.42 - > 7.0.47 at EL-Escaping ?
Java
I successfully created a spring boot Serviceclass in order to write on google sheets , following the Java Quistart Tutorial for Sheets APIMy problem is that the authorization is not renewing , so after the first successful authentication via browser , after some hours I get 401 unauthorized.How can I automatically rene...
import com.google.api.client.auth.oauth2.Credential ; import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp ; import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver ; import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver.Builder ; import c...
Google Sheets java sdk oAuth unauthorized after some hours ( spring boot )
Java
I Have two repository interfaces that connect MongoDB and CouchBase : Is there a way to interchangeably @ Autowire these repositories into UserService on condition ? The condition will be inside application.properties . Note : These repositories can have custom methods too .
public interface UserRepositoryMongo extends MongoRepository < User , Long > { } public interface UserRepositoryCouch extends CouchbasePagingAndSortingRepository < User , Long > { }
conditional repository injection - Spring Boot
Java
I am trying to sort a list of strings for a Pacific island language ( Chamorro ) . In this language , Ng is considered one letter , and it comes after N in the alphabet . How can I sort a list of words such that Nai and Nunu both come before words that begin with Ng ? UpdateThe complete alphabet is : Besides Å , Ñ , an...
A , Å , B , Ch , D , E , F , G , H , I , K , L , M , N , Ñ , Ng , O , P , R , S , T , U , Y
Custom sorting list of strings ( following Chamorro language collation rules )
Java
My question concerns safe publication of field values in Java ( as discuessed here Java multi-threading & Safe Publication ) .As I understand it , a field can be safely read ( meaning access from multiple threads will see the correct value ) if : read and write are synchronized on the same monitorfield is finalfield is...
public class Foo { private boolean needsGreeting = true ; public synchronized void greet ( ) { if ( needsGreeting ) { System.out.println ( `` hello '' ) ; needsGreeting = false ; } } }
Safe publication when values are read in synchronized methods
Java
In Java you ca n't specify that an overridden abstract method throws some exception if the original abstract method does not ( overridden method does not throw Exception . ) However in Scala you can do this since it does n't have checked exceptions . Fine , but if you use the @ throws annotation that should tip the Jav...
package myscalaabstract class SFoo { def bar ( ) : Unit } class SFoobar extends SFoo { @ throws [ Exception ] override def bar ( ) : Unit = { throw new Exception ( `` hi there '' ) } } import myscala.SFoo ; import myscala.SFoobar ; public class Foobar { public static void main ( String [ ] args ) { SFoo mySFoo = new SF...
Scala 's @ throws annotation is ignored in javac if I declare the variable as its abstract superclass
Java
the result of the following statement should give 9 : ( using java or js or c++ ) but in php the same statements will give 12 ? ! is this a bug or can anyone explain why ?
i = 1 ; i += ++i + i++ + ++i ; //i = 9 now $ i = 1 ; $ i += ++ $ i + $ i++ + ++ $ i ; echo $ i ;
pre-increment and post-increment in PHP
Java
I 'm trying to find a third solution to this question.I ca n't understand why this does n't print false.Surely , because of string interning , the `` true '' instance being modified is exactly the same one used in the print method of PrintStream ? What am I missing ? EditAn interesting point by @ yshavit is that if you...
public class MyClass { public MyClass ( ) { try { Field f = String.class.getDeclaredField ( `` value '' ) ; f.setAccessible ( true ) ; f.set ( `` true '' , f.get ( `` false '' ) ) ; } catch ( Exception e ) { } } public static void main ( String [ ] args ) { MyClass m = new MyClass ( ) ; System.out.println ( m.equals ( ...
String literals , interning and reflection
Java
I 'm currently currently working with a rather massive project with several classes of over 20 , 000 lines . This is because it was someone 's bright idea to mix in all the generated swing code for the UI with all of the functional code.I was wondering if it would incur any extra cost in terms of memory or run time , t...
public class Class1 { private Class1Util c1u ; List < String > infoItems ; ... public void Class1 ( ) { c1u = new Class1Util ( this ) ; } public void btnAction ( ActionListener al ) { ... c1u.loadInfoFromDatabase ( ) ; } } public class Class1Util { private Class1 c ; public void Class1Util ( Class1 c ) { this.c = c ; }...
Java efficiency of moving methods to another class
Java
Given a class like so : Notice that equality does not depend on both fields matching , either field works . What would be a suitable hashCode implementation for this class ?
class MyObject { private String id1 ; private String id2 ; @ Override public boolean equals ( Object o ) { if ( o == this ) return true ; if ( ! ( o instanceof MyObject ) ) { return false ; } MyObject other = ( MyObject ) o ; return id1.equals ( other.id1 ) || id2.equals ( other.id2 ) ; } }
Java hashCode from multiple fields
Java
Lets say I have two interfaces interface A and interface B : interface A has a method public int data ( ) and interface B has a method public char data ( ) .when I implement both interfaces A and B in some class C the compiler gives me an error . Is this a flaw in java ? As I presume this is one of the major reasons wh...
public interface A { public int data ( ) ; } public interface B { public char data ( ) ; }
query about interfaces in Java
Java
Why are different case bodies not automatically in their own scope ? For example , if I were to do this : the compiler would complain about local variable redefinitions . I understand I could do this : to put a block around each set of statements to be executed to put each account variable in its own scope . But why do...
switch ( condition ) { case CONDITION_ONE : int account = 27373 ; case CONDITION_TWO : // account var not needed here case CONDITION_THREE : // account var not needed here case CONDITION_FOUR : int account = 90384 ; } switch ( condition ) { case CONDITION_ONE : { int account = 27373 ; } case CONDITION_TWO : { // accoun...
Why are different case condition bodies not in different scope ?
Java
I am trying ( without luck ) to update entries for MediaStore for both audio tracks and images . I am using something like this : The above snippet works on API16- > API28 without problems.Though , on API29 it does not work . No errors are displayed on logs or messages . I am trying the above code on the API29 emulator...
ContentValues values = new ContentValues ( ) ; values.put ( MediaStore.Audio.Media.TITLE , title ) ; values.put ( MediaStore.Audio.Media.YEAR , year ) ; resolver.update ( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI , values , MediaStore.Audio.Media._ID + `` = ? `` , new String [ ] { String.valueOf ( id ) } )
Updating an entry on MediaStore does not work on Android Q / API29
Java
I 'm implementing a simple `` Play your cards right '' ( otherwise known as higher/lower ) game . In case you 've not come across it before the rules are really simple . A single suit of cards ( e.g . hearts ) are used . One card is drawn at a time and the objective is to correctly guess if the face value of the next c...
public interface PlayYourCardsRight { /** * Get the number of cards remaining with higher face values than the previously * drawn card * @ return */public abstract int getNumberCardsHigher ( ) ; /** * Get the number of cards remaining with lower face values than the previously * drawn card * @ return */public abstract ...
Java - Design advice for simple game
Java
I am trying to convert this enum to Delphi . I know that how to define enum variables but i have no idea , how can i insert a method in enum ? Or can someone suggest another way to convert this ?
public enum HTTPHeaderKey { CACHE_CONTROL ( `` Cache-Control '' ) , CONNECTION ( `` Connection '' ) , TRANSFER_ENCODING ( `` Transfer-Encoding '' ) , HOST ( `` Host '' ) , USER_AGENT ( `` User-Agent '' ) , CONTENT_LENGTH ( `` Content-Length '' ) , CONTENT_TYPE ( `` Content-Type '' ) ; private final String str ; private...
Java enum method to Delphi
Java
I have a background image I am drawing with open gl 1.0 es.The problem is when I draw this small image to the big screen I get this ... The lines / breaks in pattern are not suppose to be there . I have tried a lot of things , I thought maybe my atlas was wrong ... doubt it . I draw it from ( 0 , 0 , 50 , 50 ) which is...
GL10 gl = this.glGraphics.getGL ( ) ; gl.glClear ( GL10.GL_COLOR_BUFFER_BIT ) ; guiCam.setViewportAndMatrices ( ) ; gl.glEnable ( GL10.GL_TEXTURE_2D ) ; // Set background color // batcher.beginBatch ( Assets.mainmenuAtlas ) ; for ( int x = Assets.mmbackgroundPattern.width / 2 ; x < this.scale.getWidth ( ) + Assets.mmba...
Getting lines from GL10 drawing images next to one another , solution ?
Java
What happens in the following code ? Does the synchronization work ? This is an interview question .
class T { public static void main ( String args [ ] ) { Object myObject = new Object ( ) ; synchronized ( myObject ) { myObject = new Object ( ) ; } // end sync } }
What happens if synchronization variable is reassigned in java ?
Java
I 'm using Java 1.8.0_151 and there is some code that does n't compile and I do n't understand : why it works fine on result1 but gives compilation error on result3 ? Additional info : In the first line , when I change Optional to Optional < String > , result3 is also able to compileWhen I break result3 into 2 lines : ...
Optional optional = Optional.of ( `` dummy '' ) ; Optional < Boolean > result1 = optional.map ( obj - > true ) ; // works fineboolean result2 = result1.orElse ( false ) ; // works fineboolean result3 = optional.map ( obj - > true ) .orElse ( false ) ; // compilation error : Incompatible types : required boolean , found...
Java8 generic puzzle
Java
I have a generic java interface Id < T > with a single method T getId ( ) and a class MyClass that implements Id < Long > . When I inspect the methods declared on MyClass using java reflection , I see two methods : one with return type Long , and one with return type Object . Where does the second method come from and ...
package mypackage ; import java.lang.reflect.Method ; public class MainClass { public static void main ( String [ ] args ) { for ( Method method : MyClass.class.getDeclaredMethods ( ) ) { System.out.println ( method ) ; } // prints out two lines // public java.lang.Long mypackage.MyClass.getId ( ) < -- ok // public jav...
Implementing generic java interface adds additional method
Java
We just updated from JDK8 to JDK11 and our Tomcat started reporting this warning ( we use Docker image tomcat:9-jre11-slim ) : The bug # 56684 mentioned in the warning refers to this : https : //bz.apache.org/bugzilla/show_bug.cgi ? id=56684 - which is probably fixed and not very relevant.Can we ignore this error ? Thi...
2019-04-17 10:17:35.060 WARNING [ : tomcat ] org.apache.catalina.core.StandardServer The socket listening for the shutdown command experienced an unexpected timeout [ 256 ] milliseconds after the call to accept ( ) . Is this an instance of bug 56684 ? java.net.SocketTimeoutException : Accept timed out at java.base/java...
Tomcat socket listening timeouts
Java
We use Java beans on some projects where I work , this means a lot of handcrafted boilerplate code like this.I 'm after an Eclipse plugin , or a way of configuring Eclipse code templates that allows a developer to generate the setters from a simple skeleton class , in a similar fashion to the 'Generate Getters and Sett...
public class MyBean { private String value ; } public class MyBean { private final PropertyChangeSupport pcs = new PropertyChangeSupport ( this ) ; private String value ; public String getValue ( ) { return this.value ; } public void setValue ( String newValue ) { String oldValue = this.value ; this.value = newValue ; ...
Generating Java Bean setters in Eclipse
Java
I have a Map < String , String > which indicates links from A to B. I want to chain all possible routes . for example : will outputI found similar question here ( but not fully fulfills my requirement ) : https : //stackoverflow.com/a/10176274/298430And here is my solution : and the test case : It does work correctly :...
[ A , B ] [ B , C ] [ C , D ] [ E , F ] [ F , G ] [ H , I ] [ A , B , C , D ] [ E , F , G ] [ H , I ] public static < T > Set < List < T > > chainLinks ( Map < T , T > map ) { Set < List < T > > resultSet = new HashSet < > ( ) ; map.forEach ( ( from , to ) - > { if ( ! map.containsValue ( from ) ) { List < T > list = n...
java 8 functional style of chaining links
Java
How can I catch the final exception that caused the Camel failover load balancer to fail ( e.g . to prepare a nice ( HTTP ) response instead of plain stack trace ) ? I have something like this : with : ( and exactly the same for `` direct : bar ) Without the load balancing I 'd go ahead and use onException but I ca n't...
from ( `` jetty : http : //0.0.0.0:8081/context '' ) .process ( frontendProcessor ) .loadBalance ( ) .failover ( 1 , false , true , true , MyFancyException.class ) .to ( `` direct : foo '' , `` direct : bar '' ) .end ( ) .process ( responseProcessor ) .stop ( ) ; from ( `` direct : foo '' ) .process ( potentiallyThrowi...
How to handle failover load balancer failure in Camel ?
Java
I have controller : and jsp page : It works fine , but I confused , when railwayServiceRepository.findOne ( id ) return null NullPointerException does n't throw .
@ RequestMapping ( method = RequestMethod.GET ) public String getViewRailwayService ( @ RequestParam long id , Model model ) { model.addAttribute ( `` railwayService '' , railwayServiceRepository.findOne ( id ) ) ; return `` admin/railwayService/view '' ; } ... < title > $ { railwayService.name } < /title > < c : forEa...
JSP not throwing NullPointerException
Java
I 'm upgrading production hardware , and we 're seeing far more young-gen GCing on the new set of kit compared to the old.The same program is running ( identical binaries ) on both machines . One obvious difference ( I hope this does n't make a difference to the JVM ) is that we have upgraded RHEL5 - > RHEL6.Our JVM ( ...
-XX : +PrintGC -XX : +PrintGCDetails -XX : +PrintGCTimeStamps -XX : +UseParallelGC -XX : +UseCompressedOops -Xmx1024M -Xms1024M -XX : NewSize=512M -XX : SurvivorRatio=2 grep `` PSYoungGen '' ./log | wc -l
Does increasing the number of available cores and RAM cause the JVM to perform more GCs ?
Java
When you compile a Java class with a private inner class , it appears that an anonymous class is automatically synthesized along with it for some reason . This class is sufficient to reproduce it : When compiled , this generates the expected SynthesizeAnonymous.class and SynthesizeAnonymous $ InnerClass.class files , b...
public class SynthesizeAnonymous { public static void method ( ) { new InnerClass ( ) ; } private static class InnerClass { } }
Private inner class synthesizes unexpected anonymous class
Java
For one of our project , we are consuming HTTP feed stream by using java jersey clientWith the client Feed consuming is fine , but after the 10 mins of time , stream dropping abnormally ; even though stream producer is up and running and producing the streamThis is what I tried ; If stream does n't drop ; thread has to...
import java.util.Date ; import javax.ws.rs.client.Client ; import javax.ws.rs.client.ClientBuilder ; import javax.ws.rs.client.WebTarget ; import javax.ws.rs.client.Invocation.Builder ; import javax.ws.rs.core.GenericType ; import javax.ws.rs.core.MediaType ; import javax.ws.rs.core.Response ; import org.glassfish.jers...
HTTP Stream dropping abnormally with java jersey client
Java
Let me be clear , the method I describe below is operational . I 'm hoping to improve the throughput of the method . It works , and it works quite well . We 're looking to scale throughput even more which is why I 'm looking into this.The task at hand is to improve the performance of a scoring algorithm which returns t...
final double [ ] bestScore = { Double.MAX_VALUE } ; // for each item in the collection { tasks.add ( Executors.callable ( new Runnable ( ) { public void run ( ) { double score = // ... do the scoring for the task if ( score < bestScore [ 0 ] ) { synchronized ( bestScore ) { if ( score < bestScore [ 0 ] ) { // check aga...
Using Java multithreading , what is the most efficient to coordinate finding the best result ?
Java
Consider following interface.Is above interface a bad design ? OperationResult and OperationInput are defined as static class . They would be only used by implementations and not anywhere else . Advantage that I see here is - I do n't have to create separate files for these two classes . Also they get namespace of pare...
public interface ThirdPartyApiHandler { public OperationResult doOperation ( OperationInput input ) ; public static class OperationResult { //members of OpeationResult . metrics after file processing private int successfulRecords ; private int failedRecords ; } public static class OperationInput { //implementations cal...
Java Interface - constants and static class in normal interface
Java
Here 's the scenario . As a creator of publicly licensed , open source APIs , my group has created a Java-based web user interface framework ( so what else is new ? ) . To keep things nice and organized as one should in Java , we have used packages with naming conventionorg.mygroup.myframework.x , with the x being thin...
[ org.mygroup.myframework . * ] void doStuff ( ) { ... . } package org.mygroup.myframework.foo ; public class Bar { /** Adds a Bar component to application UI */ public boolean addComponentHTML ( ) { // Code that adds the HTML for a Bar component to a UI screen // returns true if successful // I need users of my framew...
The missing `` framework level '' access modifier